#include<stdio.h>
#include<stdlib.h>
typedef struct treenode{
int elem;
int color;
struct treenode *left,*right,*parent;
}treenode_t;
treenode_t *create_node(int elem){
treenode_t *newnode=(treenode_t *)malloc(sizeof(treenode_t *));
newnode->elem=elem;
newnode->left=NULL;
newnode->right=NULL;
newnode->color=0;
newnode->parent=NULL;
return newnode;
}
void insert(treenode_t **node,int elem){
if(*node==NULL){
*node=create_node(elem);
}else{
treenode_t *store_parent;
treenode_t *ptr;
ptr=*node;
while(ptr!=NULL){
store_parent=ptr;
if(elem<ptr->elem){
if(ptr->left==NULL){
ptr->left=create_node(elem);
(ptr->left)->parent=store_parent;
(ptr->left)->color=1;
}
ptr=ptr->left;
}
else if(elem>ptr->elem){
if(ptr->right==NULL){
ptr->right=create_node(elem);
(ptr->right)->parent=store_parent;
(ptr->right)->color=1;
}
ptr=ptr->right;
}
}
}
}
void print_tree(treenode_t *node){
if(node==NULL)
return;
print_tree(node->left);
printf("%d\n",node->elem);
print_tree(node->right);
}
void main(){
treenode_t *root=NULL;
insert(&root,10);
insert(&root,5);
insert(&root,14);
print_tree(root);
}
I am able to insert the first element but the second time the malloc fails.
Using GDB: When i use gdb i found that once i have created the first node(the root of the tree), when i go insert the second element i.e. 5 the line ptr->left=create_node(elem) redirects to the function create_node().The address which is allocated to malloc is the same as that is stored in the root which results in the error.
I get the following error:
a.out: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Program received signal SIGABRT, Aborted. 0x00007ffff7a4af79 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56 56 ../nptl/sysdeps/unix/sysv/linux/raise.c: No such file or directory.
Now do i have to change the address the of the memory that is allocated by malloc(if so,how?) or is there some other problem in the code?