Reputation:
I have implemented a C calculator to analyses input. I have a struct (like a chained list) but on macOS I have to initialise through the init_null function or variable like value have an initial value. I have just one question: why?
On Linux, there was no issues.
typedef struct node_t {
int value;
char operator;
struct node_t *left;
struct node_t *right;
} node_t;
node_t *init_null(node_t *root) {
root->value = NULL;
root->operator = NULL;
root->left = NULL;
root->right = NULL;
return root;
}
node_t *build_tree(const char *argv[], int *position) {
node_t *new = malloc(sizeof(node_t));
new = init_null(new); /*sinon erreur*/
if (isdigit(*argv[*position])) {
new->value = atoi(argv[*position]);
} else/*Opérateur*/ {
new->operator = *argv[*position];
*position = *position + 1;
new->left = build_tree(argv, position);
*position = *position + 1;
new->right = build_tree(argv, position);
}
return new;
}
When run, ./main * 2 + 3 4
should print (2 * (3 + 4))
.
Upvotes: 2
Views: 434
Reputation: 1032
Here is the problem:
There are at least 2 memory allocation methods you can use, malloc
and calloc
. The difference is that malloc
DOES NOT initialise (or set) the successfully allocated memory to anything. There is an indeterminate explicit or implicit effect on the memory block, specific to the compiler at this compilation stance, as @EricPostpischil explained.
Whereas calloc
sets the successfully allocated memory block to zero. Note that the arguments are slightly different.
Back to your concern, in Linux malloc
just happened to allocate a block of memory that had zero in it, whereas on the macos platform there was something in it.
Use calloc
if you thing you need it, otherwise do a memset
of 0 to the allocated memory block.
Upvotes: 2