Lesson 28 / 36

malloc, calloc, realloc, free

Request and release memory from the heap at runtime.

The heap vs the stack

Local variables live on the stack and vanish automatically. The heap is memory you request explicitly with malloc-family functions, and it stays reserved until you free it.

malloc + free

malloc(n) returns raw, uninitialised memory (or NULL on failure). Always pair it with free once done.

int *arr = malloc(5 * sizeof(int));
if (arr == NULL) {
    return 1; // allocation failed
}

for (int i = 0; i < 5; i++) arr[i] = i * i;
printf("%d\n", arr[4]);

free(arr);
arr = NULL;

Output:

16

calloc vs realloc

calloc(n, size) allocates and zeroes the memory. realloc(ptr, newSize) grows or shrinks an existing block, copying old data over — always reassign its result, since the block may move.