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:
| Parameter | Type | Description |
|---|---|---|
| malloc(size) | Function | Allocates uninitialized byte block on heap. |
| free(ptr) | Function | Releases allocated heap memory back to OS. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C Pointers: Memory Addresses, Dereferencing (*), and Pointer Arithmetic
Master pointers in C: address-of (&), dereferencing (*), pass-by-reference simulation, and pointer math.
C File I/O: fopen, fread, fwrite, and fclose
Read and write disk streams using standard C FILE* handles, fopen, and fclose.
C Arrays: Contiguous Stack Buffers and Multi-Dimensional Arrays
Learn fixed-size arrays, memory layouts, indexing, and calculating element counts.
C Online Compiler
Open in Compilra IDE
Run and test C on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.