Shallow copy and deep copy in C

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

Leave a Comment