Set your Publisher ID in src/config/ads.ts to display live ads.
Dynamic Memory Allocation: malloc, calloc, realloc & free
Heap memory allocation, memory leaks, and dangling pointer prevention
Dynamic memory enables programs to request arbitrary bytes from the operating system Heap at runtime via <stdlib.h>. Every allocated byte must be manually freed.
The Heap Allocation Lifecycle
malloc(size_in_bytes): Allocates uninitialized memory on the heap. Always check if the returned pointer is NULL (out of memory)!
calloc(num_elements, size): Allocates memory and initializes all bytes to zero.
realloc(ptr, new_size): Resizes an existing heap allocation.
free(ptr): Releases allocated memory back to the OS. Failing to call free causes a Memory Leak.
Best Practice: Immediately after free(ptr), assign ptr = NULL; to prevent Dangling Pointer bugs.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 5;
// Allocate array of 5 integers on Heap
int *arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "Out of memory error!\n");
return 1;
}
for (int i = 0; i < n; i++) {
arr[i] = (i + 1) * 10;
printf("arr[%d] = %d\n", i, arr[i]);
}
// Free allocated memory to prevent memory leak!
free(arr);
arr = NULL; // Defend against dangling pointer
return 0;
}Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
What occurs if a C program continuously allocates heap memory with `malloc()` but never calls `free()`?