Quiz Entry - updated: 2026.07.10
How do you allocate memory dynamically in C?
Call malloc(bytes) to grab heap memory (check it for NULL), use it, then free() it exactly once when done.
#include <stdlib.h>
// Allocate array of 10 ints
int *arr = malloc(10 * sizeof(int));
if (arr == NULL) {
// Allocation failed!
return -1;
}
// Use the memory
arr[0] = 42;
arr[9] = 100;
// Free when done
free(arr);
// Good practice: avoid dangling pointer
arr = NULL;
Common allocation functions:
// Allocate size bytes (uninitialized)
malloc(size)
// Allocate and zero-initialize
calloc(count, size)
// Resize existing allocation
realloc(ptr, newsize)
// Deallocate
free(ptr)
Common mistakes:
// Forgetting to check for NULL
int *p = malloc(sizeof(int));
// Crash if malloc failed!
*p = 5;
// Memory leak - forgetting to free
void leak() {
int *p = malloc(100);
// Memory never freed!
return;
}
// Use after free
free(p);
// UNDEFINED BEHAVIOR!
*p = 5;
// Double free
free(p);
// UNDEFINED BEHAVIOR!
free(p);
Go deeper:
C dynamic memory allocation — Wikipedia — malloc/calloc/realloc/free and the classic allocation bugs.