0
generic programming understanding memory ownership
I understand that when doing generic programming in c , I mostly will need to be understand void* use , function pointers , to do so I tried to switch an intBST to a generic one , and the thing that i am trying to get clarified is the need for a deep copy function , for example the data can be string or int so i need to use a void * the data entered i assume will be dependent on the scope so it may be freed from the stack and i am pointing to a garbage so i need to control when that data will be freed and thats why i want store it on heap is the intuition correct , and mostly would appreciate any intuition
3 Antwoorden
+ 3
Dareen Moughrabi yes, confirming your thinking, heap allocation is necessary within the deep copy function. It is the only way the memory will remain allocated after the copy function returns.
I suppose your generic BST node struct defines a type field that indicates to the copy function whether to allocate and copy an int or a string, else the type must get passed as a parameter to the copy function. Or are there multiple copy functions defined according to node type?
Another option besides void* is to use a union within the BST node struct.
union {
int i;
char* s;
} data;
+ 2
Brian
Thanks for the confirmation
As for the bst i made it such that there are multiply copy functions defined according to data type , and the user gets a message with the name of the functions i built
And then he has to give the correct functions to deal with the data type he is inserting to the bst , so struct containg the pointer to functions that will be provided by the user
And the node struct has a field for data being void *
So the code functions for both but inputed functions change
And i always forget union exists i need to keep that in mind for simpler applications thanks
0
Dareen Moughrabi ,Youâve got the right idea! When you store void* in a generic structure, you donât know if the original variable lives on the stack or the heap. If itâs a stack variable, it can disappear once the scope ends, and then your pointer would be dangling (pointing to garbage).
Thatâs why generic data structures usually:
Deep copy the data â so the structure owns its own copy on the heap.
Provide a free function â so the structure also knows how to safely release that memory later.
In practice, this is handled by passing function pointers (copy/free) when you create the structure. That way, the BST doesnât care what type the data isâit just relies on those functions.
So yes, your intuition is correct: deep copy ensures safe ownership of the data and prevents pointing to freed memory.