Code
An array that grows
How many squares are below 1000? We "don't know" the answer in advance, so the array grows until the squares run out. copy_string stays the same.
memory.c:
typedef struct { int *data; int count; int capacity; } IntArray;array_init(&m)– an empty array:NULL, 0, 0.array_add(&m, x)– whencount == capacity, the capacity is doubled throughreallocand a temporary pointernew_data; so you can see when it happens, the function printsCapacity: 4 -> 8. It returns 0 if it got no memory.array_free(&m)–free, and the array is empty again.- At the start of
main, instead of the fixedmalloc– a loopfor (int i = 1; i * i < 1000; i++)witharray_add, the results andarray_free.
Run it
Capacity: 0 -> 4
Capacity: 4 -> 8
Capacity: 8 -> 16
Capacity: 16 -> 32
Squares below 1000: 31, capacity 32
Last: 961
Copy: Ona Petraite (13 bytes)
Four realloc calls for 31 elements, not 31. One place (the 32nd) stayed empty.
realloc in the debugger
A breakpoint at m->data = new_data;, Debug. Each time compare m->data and new_data: sometimes the address is the same (the block grew in place), sometimes different (realloc moved the data). That's why you can't keep a pointer to the old block somewhere else – after realloc it may point at freed memory.
Commit: Grow array with realloc.