Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c copy struct with pointers from stack to heap

Tags:

c

heap-memory

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?

like image 880
Seneca Avatar asked Sep 20 '25 13:09

Seneca


1 Answers

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.

like image 175
Abhijit Pritam Dutta Avatar answered Sep 22 '25 19:09

Abhijit Pritam Dutta