Given the following type
typedef struct {
const void *data;
uint32_t offset[2];
} TSNode;
I've got a function which contains an assignement:
TSNode* myFun() {
TSNode node = get_node();
// rest of code
}
Since node
is allocated on stack memory here, it'll vanish once the function has ended. I want to keep track of that node at later points, so I thought to just copy it to the heap.
TSNode* myFun() {
TSNode node = get_node();
TSNode* heapNode = malloc(sizeof(TSNode));
memcpy(heapNode, &node, sizeof(TSNode));
return heapNode;
}
Does this memcpy all data correctly to my heap allocated heapNode
?
i.e. nothing is corrupted in the process & the *data
is intact?
Does this memcpy all data correctly to my heap allocated heapNode? i.e. nothing is corrupted in the process & the *data is intact?
The answer to this question is, memcpy
use shallow copy
concept. In shallow copy
the pointer in your original structure (node) TSNode node = get_node();
will be copied to the new node heapNode
(TSNode* heapNode
) bit by bit also call bit wise copy. So your new heapNode
pointers will also pointing to the same location as your original node's (TSNode node = get_node();
) pointers from where you copied the value with memcpy
. Hence once control returns from function myFun
your original node will be released from memory. Therefore your new node pointers will become dangling pointers
. That is a critical side effect of memcpy
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With