This is the code in C, compiled on Ubuntu 15.10:
----- node_tree.h -----
struct node_tree{
int key;
char value[20];
struct node_tree* right_child;
struct node_tree* left_child;
};
typedef struct node_tree* node;
----- tree_test_main.c -----
#include "node_tree.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <time.h>
int main(){
//root
node root = malloc(sizeof(node));
root->key = 1;
strcpy(root->value, "Ciao");
//left child
node left = malloc(sizeof(node));
left->key = 2;
strcpy(left->value, "Maremma");
//right child
node right = malloc(sizeof(node));
right->key = 3;
strcpy(right->value, "Maiala");
root->left_child = left;
root->right_child = right;
printf("%d, %s\n", root->key, root->value);
printf("%d, %s\n", root->left_child->key, root->left_child->value);
printf("%d, %s\n", root->right_child->key, root->right_child->value);
free(root);
free(right);
free(left);
}
This is the console output, I can't understand why the string '8446000' appears. I tried the same code on Mac OS X and it works fine.
1, Ciao
8446000,
3, Maiala
*** Error in `./a.out': free(): invalid next size (fast): 0x000000000080e010 ***
[1] 3926 abort (core dumped) ./a.out
typedef. You have to type less, but tend to forget what the actual type of the thing is.typedeftogether withstructis entirely a style matter. Most C programmers usetypedef struct, except Linux programmers who prefer not to. Neither style is wrong. However, hiding a pointer behind a typedef is not a style matter, but simply bad and dangerous programming practice.