This is my code. I thought I will be getting a SegFault on b2->x.pointer1->data because I didn't malloc the b2->x.pointer1. Can anybody please give me some explanation to it? What values were copied to b2->x.pointer1 while doing memcpy? And also regarding the book-keeping of struct *b2 particularly which was filled by memcpy, that how it kept a record of its members? All my motive is to know that how b2->x.pointer1 got its memory on heap.
struct A
{
int data;
};
struct B
{
int data;
union X
{
struct A *pointer1;
//another
}x;
};
int main(int argc, char **argv)
{
struct B *b1 = (struct B*) malloc(sizeof(struct B));
b1->data = 100;
b1->x.pointer1 = (struct A*) malloc(sizeof(struct A));
b1->x.pointer1->data = 1;
struct B *b2 = (struct B*) malloc(sizeof(struct B));
//b2->x.pointer1 = (struct A*) malloc(sizeof(struct A));
memcpy(b2, b1, sizeof(struct B));
printf("%d", b2->x.pointer1->data);
return 0;
}
And what if I'll free(b1)? Will it free the b1->x.pointer1 too or will there be some memory leak here?