I have the following structure that I've declared:
typedef struct binTreeNode
{
void *data;
struct binTreeNode *left;
struct binTreeNode *right;
} myBinaryTreeNode;
In my main
function, I'm trying to use a pointer to an instance of that structure called root
.
myBinaryTreeNode *root = malloc(sizeof(myBinaryTreeNode));
printf("\nPlease insert root data: ");
int input;
scanf("%d", &input);
root->data = (void*)&input;
printInt(root->data);
free(root);
this code runs perfectly well. But, I thought that when you have a struct with members that are pointers, you should free()
each one of them (additionally to the pointer to the struct).
So here, I didn't malloc
for root->data
(because I think that malloc
ing the struct does that), but it is initialized to the input value and it's value gets printed successfully. When I try to free(root->data)
my program crashes.
So root->data
is not malloc
ed when I malloc root
? If not, how can I still use it?
Why does this happen? What am I missing here?