I've come up with a problem where I do not give enough memory to my node after the first one when I do, for example, firstNode = (node)malloc(sizeof(node))
.
The following is the structure of *node and the insert function that uses the malloc function.
typedef struct treeNode *node;
struct treeNode {
node left;
node right;
int data;
};
node firstN;
node secondN;
node insert(int a, node t){
if(t==NULL){
t = (node)malloc(sizeof(node));
t->data = a;
t->left = NULL;
t->right = NULL;
} else {
if(a < t->data){
t->left = insert(a, t->left);
}else if(a > t->data){
t->right = insert(a, t->right);
}
}
return t;
}
Here is the main() where I tested the inserting process with malloc (I did not use the insert function defined above, because I was still testing line by line in the main).
firstN=(node)malloc(sizeof(node)*10);
firstN->data=1;
firstN->right=NULL;
firstN->left=NULL;
firstN->right=(node)malloc(sizeof(node)*10);
Interesting thing for me is that while the above works, just normally doing (node)malloc(sizeof(node)) (without the multiply by 10) does not work for the second instance, firstN->right.
I wonder why the code is not giving enough memory, if that is the correct case.