Memory Management
Allocate, resize, and free heap memory with malloc, realloc, and free.
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
Pointer Basics
Declare pointers, dereference, and walk an array with pointer arithmetic.
String Operations
Use string.h helpers for length, copy, concat, compare, and tokenize.
File I/O
Open, read, write, and close files using the stdio FILE API.
Structs
Group related fields with typedef and pass by pointer for mutation.
Function Pointers
Store function addresses for callbacks and dispatch tables.
Preprocessor Macros
Define object-like and function-like macros with conditional compilation.