Reputation: 19
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
Upvotes: 1
Views: 529
Reputation: 9699
You need to allocate the right size:
node N = malloc(sizeof *N);
Try to print their size to see it:
printf("sizeof N = %zu", sizeof N);
printf("sizeof *N = %zu", sizeof *N);
EDIT: replaced type with variable.
Upvotes: 1
Reputation: 16047
This is one of the reasons you should not hide pointers behind typedef.
sizeof(node)
returns sizeof(struct node_tree*)
, not sizeof(struct node_tree)
as you expect.
Change the typedef to not hide the pointer:
typedef struct node_tree node;
And to be safe, allocate using variable rather than type:
node * root = malloc(sizeof(*root));
Upvotes: 2
Reputation: 28685
node root = malloc(sizeof(node));
This allocates size for the pointer, not the structure. Try this:
node root = malloc(sizeof(*root));
Similarly for other variables.
Upvotes: 3
Reputation: 75062
node
is a pointer type and its size will be less than size of the struct, so there are insufficient space allocated and you are accessing out-of-range.
Try using sizeof(struct node_tree)
instead of sizeof(node)
.
I suggest you should stop using typedef
to the pointer to avoid confusion.
Upvotes: 2