Using memcpy to copy a structure into the heap


I am trying to put a structure named "Holder" into the heap by using the following code, but I get a segmentation fault when I try to use memcpy:

Holder hold;
Holder *heapHold = memcpy(heapHold, &hold, sizeof(Holder));

Why do I segfault?

Best Solution

Holder hold;

This declares hold as a variable of type Holder. hold is uninitialized.

Holder *heapHold = memcpy(heapHold, &hold, sizeof(Holder));

memcpy(dest, source, size) copies size bytes from source to dest. It assumes that dest is properly allocated. Since you don't allocate memory for it, you get a segfault.

You need to allocate memory:

Holder *heapHold = malloc(sizeof *heapHold);
if (heapHold == NULL) {
    /* failed to allocate, handle error here */
} else {
    /* OK to copy.  Make sure you initialize 'hold' to something valid */
    memcpy(heapHold, &hold, sizeof *heapHold);

Also, memcpy() returns the first parameter. Assigning the return value to heapHold is just like saying a = a;, i.e., it doesn't do anything. For most practical cases, the return value of memcpy() is ignored.

Related Question