C:C Dynamic Memory: malloc, calloc, realloc, and free
C•Dynamic Memory

C Dynamic Memory: malloc, calloc, realloc, and free

Learn manual memory management on the heap, checking for allocation failure (NULL), and avoiding memory leaks.

Syntax

int* arr = (int*)malloc(n * sizeof(int)); free(arr);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
malloc(size)FunctionAllocates uninitialized byte block on heap.
free(ptr)FunctionReleases allocated heap memory back to OS.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

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

int main(void) {
    int capacity = 3;
    // Allocate buffer on heap
    int* buffer = (int*)malloc(capacity * sizeof(int));

    if (buffer == NULL) {
        printf("Memory allocation failed!\n");
        return 1;
    }

    buffer[0] = 100;
    buffer[1] = 200;
    buffer[2] = 300;

    printf("Initial Heap Buffer:\n");
    for (int i = 0; i < capacity; i++) {
        printf("  buffer[%d] = %d\n", i, buffer[i]);
    }

    // Free allocated memory
    free(buffer);
    buffer = NULL; // Prevent dangling pointer
    printf("Heap memory freed safely.\n");

    return 0;
}
Expected Output:
Initial Heap Buffer:
  buffer[0] = 100
  buffer[1] = 200
  buffer[2] = 300
Heap memory freed safely.

How It Works: Step-by-Step

  • Lines 7-13: malloc allocates 3 * sizeof(int) bytes on the heap and checks for NULL.
  • Lines 15-22: Fills and reads heap buffer.
  • Lines 25-26: free(buffer) releases memory and sets pointer to NULL.

Key Concepts

  • malloc leaves memory uninitialized; calloc zeroes all allocated bytes.
  • Every malloc call must have a corresponding free call to avoid memory leaks.
  • Always set pointers to NULL after freeing to prevent use-after-free bugs.

Common Mistake: Memory leak by losing pointer reference without calling free()

Overwriting a pointer before freeing the allocated memory permanently leaks RAM.

❌ Incorrect
int* p = malloc(100); p = malloc(200); // First 100 bytes are leaked forever!
✅ Correct
int* p = malloc(100); free(p); p = malloc(200); free(p);

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler