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?
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.
You need to allocate memory for heapHold
first. Currently memcpy is writing to some random address (heapHold
is uninitialized), causing the crash.
Holder hold;
Holder *heapHold = malloc(sizeof(Holder));
memcpy(heapHold, &hold, sizeof(Holder));
Holder hold;
Holder *heapHold = malloc(sizeof(Holder));
memcpy(heapHold,&hold,sizeof(Holder));
The heapHold
variable in memcpy(heapHold, &hold, sizeof(Holder));
is still not initialized (and no buffer was allocated what-so-ever) so it's pointing to invalid memory.
BTW (I always forget to mention that) - when you allocate memory using malloc
, don't forget
to free it later..
精彩评论