I'm new to C and work myself throug the MIT Open Courseware for practical C programming (MIT OCW Homepage) in order to learn some C basics.
In assignment 5 we are supposed to implement a small binary tree library for allocation, deallocation, display and traversal.
While testing the following implementation
#include <stdlib.h>
struct TreeNodeStruct {
int data ;
struct TreeNodeStruct *left, *right ;
} ;
typedef struct TreeNodeStruct TreeNode ;
TreeNode* talloc(int data)
{
/* variables */
TreeNode *p ;
/* logic */
p = malloc(sizeof(struct TreeNodeStruct)) ;
p->data = data ;
/* return */
return p ;
}
TreeNode* addnode(TreeNode* root ,int data)
{
/* logic */
if(root == NULL) return talloc(data) ; // allocate node and return as new root
else if(data < root->data) root->left = addnode(root->left, data) ;
else root->right = addnode(root->right, data) ;
/* return */
return root ;
}
in a very simple test case
printf("\nProblem 5.2\n") ;
tree = talloc(0) ;
printf("talloc(0): %s\n", tree == NULL ? "failure" : "success") ;
for(int i1 = 0, i2 = 10; ++i1 < i2 ; ) addnode(tree, i1) ;
I run into a segmentation fault 11 error. Is this an artefact of my test case or an error in my implementation? If it is, what am I doing wrong?
callocinstead ofmalloc. It will initialize the members of the node with zeros. And usesizeof *pinstead ofsizeof(struct TreeNodeStruct).sizeofis compile-time.