0

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
WhiteSword
  • 101
  • 9

2 Answers2

3

The free function doesn't know anything about the content of the memory being freed.

In other words free(b1) will simply free the memory b1 points to, resulting in a memory leak because b1->x.pointer1 has not been freed and cannot be accessed anymore.

You need to free b1->x.pointer1 explicitly before freeing b1.

Correct sequence for freeing:

free(b1->x.pointer1);
free(b1);
free(b2);

The rule of thumb is: everything that has been allocated by malloc needs explicitely to be freed with free.

Concerning b2: after the memcpy, the content of *b2 is exactly the same as the content of *b1, so b2->x.pointer1 points to the exact same location as b1->x.pointer1, therefore free(b2->x.pointer1); must not be done once free(b1->x.pointer1); has been done. Freeing twice the same memory results in undefined behaviour (most likely a crash).

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
1

In addition to Michael Walz's answer...

Can anybody please give me some explanation to it?

memcpy does a bit by bit copy of the specified number of bytes. That's why you don't segfault. If you go down and look in the memory, you will find that the bits in b2 have become exactly same as b1.

What values were copied to b2->x.pointer1 while doing memcpy?

The data copied will be same as source (b1 in this case) from where you are copying. For the computer, b1 and b2 are just two different locations which have the same bit pattern.

babon
  • 3,615
  • 2
  • 20
  • 20