Shallow copy and deep copy in C

ShadyBears picture ShadyBears · Mar 7, 2013 · Viewed 37.7k times · Source

I tried googling this but only objected oriented languages pop up as results.

From my understanding a shallow copy is copying certain members of a struct.

so lets say a struct is

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

copying the char** would be a shallow copy

but copying the whole linked list would be a deep copy?

Do I have the right idea or am I way off? Thanks.

Answer

user529758 picture user529758 · Mar 7, 2013

No. A shallow copy in this particular context means that you copy "references" (pointers, whatever) to objects, and the backing store of these references or pointers is identical, it's the very same object at the same memory location.

A deep copy, in contrast, means that you copy an entire object (struct). If it 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's not anymore the same pointer