#include #include /**** * A tiny little program to would with making deep and shallow copies and then freeing * everything. **/ // A trully meaningless struct typedef struct { int payload; } LL; /** * Create (dynamically allocate) an instance of the struct **/ LL* makeLL() { LL* ll = malloc(sizeof(LL)); ll->payload=rand()%1000; // give the struct some data. return ll; } /** * Make a deep copy of the struct. * To do so, make a new struct, then copy the contents of the original struct ti the new one * Since the contents is just an int, this is quite trivial **/ LL* replicate(LL* c) { LL* ll = malloc(sizeof(LL)); ll->payload=c->payload; return ll; } int main(void) { srand(42); // First create an array of 100 items LL** arr = malloc(100 * sizeof(arr)); // more use of arr in malloc for (int i=0; i<100; i++) arr[i] = makeLL(); // pointer copy LL** carrp = arr; // make a shallow Copy LL** carrsh = malloc(100 * sizeof(carrsh)); // more use of arr in malloc for (int i=0; i<100; i++) carrsh[i]=arr[i]; // make a deep copy LL** carrdeep = malloc(100 * sizeof(carrdeep)); // more use of arr in malloc for (int i=0; i<100; i++) carrdeep[i]=replicate(arr[i]); for (int i=0; i<100; i++) { free(carr[i]); // no free for carrsh[i] free(carrdeep[i]); } free(carr); // no free for carrp free(carrsh); free(carrdeep); }