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?
get_node();?memcpywould corrupt anything? But this is somewhat odd, please showget_node(), depending on that you might need to do things differently alltogether.memcpyjust copies the whole struct byte per byte and this is exactly what we want. Manually copying each field is also possible, but it's slower and error prone.*heapnode = node;. I think that was part of the first ANSI C version (The original Kernighan/Ritchie C allowed only two things with a struct: Applying the.operator and the&operator. No assignment, no parameter passing). That is, it has been available for 39 years. I feel old.