Shallow copy and deep copy in C

I tried a search on Google, but only the languages โ€‹โ€‹targeted to it appear as results.

In my opinion, a shallow copy copies certain structural elements.

so let's say that struct

typedef struct node { char **ok; int hi; int yep; struct node *next; }node_t 

copying char ** will be a shallow copy

but copying the entire linked list will be deep?

Do I have the right idea or am I leaving? Thanks.

+8
c deep-copy shallow-copy
source share
2 answers

Not. A shallow copy in this particular context means that you are copying "links" (pointers, whatever) to objects, and the backup storage of these links or pointers is identical, it is the same object in the same memory location.

Deep copy, in contrast, means that you are copying the entire object (struct). If he has members that can be copied shallow or deep, you also make a deep copy of them. Consider the following example:

 typedef struct { char *name; int value; } Node; Node n1, n2, n3; char name[] = "This is the name"; n1 = (Node){ name, 1337 }; n2 = n1; // Shallow copy, n2.name points to the same string as n1.name n3.value = n1.value; n3.name = strdup(n1.name); // Deep copy - n3.name is identical to n1.name regarding // its *contents* only, but it not anymore the same pointer 
+13
source share

The copy constructor is used to initialize a new object with a previously created object of the same class. By default, the compiler wrote a shallow copy. A shallow copy works fine when dynamic memory allocation is not used, because when allocating dynamic memory, both objects point to the same memory location on the heap, so to remove this problem we wrote a deep copy so that both objects have their own copy of the attributes in memory . To read the details with full examples and explanations, you can see part of this article about the difference between Shallow and Deep copy constructors .

0
source share

All Articles