Clone

1

Move, Copy, and clone

5 minute

C developers often read assignment and parameter passing as copying a value:

uint32_t a = 10;
uint32_t b = a;

Struct values can also be copied:

struct Point p1 = {1, 2};
struct Point p2 = p1;

But once a struct contains a pointer, the meaning changes:

struct Buffer {
    uint8_t *data;
    size_t len;
};

struct Buffer b2 = b1; // only copies pointer and length

That is not a deep copy. b1.data and b2.data point to the same allocation. Who frees it? Can both mutate it? Can one still use it after the other frees it? C handles this by convention.

Read More