Dynamic Memory Management

realloc

/ REE-alock /

Suppose you allocated a buffer for 10 items, filled it, and now discover you need room for 20. You do not want to lose the 10 you already have. realloc is the function that resizes an existing allocation — growing it (or shrinking it) while preserving the contents that fit. The name is reallocate.

Precisely: realloc(p, newsize) takes a pointer p that you got from an earlier malloc/calloc/realloc, and a new size in bytes, and returns a pointer to a block of newsize bytes that holds a copy of the old data (up to the smaller of the old and new sizes). It may do this in one of two ways, and crucially you do not get to choose: if there is room to extend the block in place, it returns the same address; otherwise it allocates a fresh, larger block somewhere else, copies your data into it, frees the old block, and returns the new address. So the old pointer p may become invalid. The correct pattern is to assign the result to a temporary first, because realloc can also fail and return NULL while leaving the original block intact — if you wrote p = realloc(p, n) and it failed, you would overwrite p with NULL and leak the original block. New bytes added when growing are uninitialized, like malloc.

realloc is the engine behind a growable array (a dynamic array, sometimes called a vector). A common strategy is to double the capacity each time it fills, so the average cost of appending stays small. Two edge cases: realloc(NULL, n) behaves exactly like malloc(n), and realloc(p, 0) is a request to release the block (its exact behavior is implementation-defined in modern C, so prefer free for that). Each successful realloc still leaves you owning exactly one live block that you must eventually free.

int *tmp = realloc(arr, newcap * sizeof *arr); if (tmp == NULL) { /* arr is still valid here */ free(arr); return -1; } arr = tmp; /* only now is it safe to overwrite arr */

Assign to a temporary first: if realloc fails it returns NULL but leaves the old block alive, so p = realloc(p, n) would leak it.

After a successful realloc, any other pointers into the old block are dangling — the block may have moved. Re-fetch all pointers from the returned address.

Also called
reallocateresize allocation重新配置