Skip to content
C

Memory Management

Allocate, resize, and free heap memory with malloc, realloc, and free.

By EZ4Code Team
memorymallocfree

Code

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    // Allocate space for 5 ints
    int *arr = malloc(5 * sizeof(int));
    if (!arr) {
        perror("malloc");
        return 1;
    }

    for (int i = 0; i < 5; i++) arr[i] = i * i;

    // Grow the buffer
    int *tmp = realloc(arr, 10 * sizeof(int));
    if (!tmp) { free(arr); return 1; }
    arr = tmp;
    for (int i = 5; i < 10; i++) arr[i] = i * i;

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

    free(arr);   // always release
    arr = NULL;  // avoid dangling pointer
    return 0;
}

Explanation

malloc returns uninitialized heap memory and free returns it to the allocator; mismatched calls cause leaks or corruption. realloc resizes a block, possibly moving it, so always reassign through a temporary to avoid losing the original on failure. Setting a freed pointer to NULL makes subsequent accidental dereferences crash loudly instead of silently corrupting memory.

More C Snippets