Dynamic Memory AllocationBeginner
1Question 1 of 1
cHow do dynamic memory allocation functions (malloc, calloc, realloc, free) operate in C?
Explanation & Concept
• `malloc(bytes)`: Allocates uninitialized memory on the heap. • `calloc(n, size)`: Allocates memory and zeroes out all bytes. • `realloc(ptr, new_size)`: Resizes an existing heap allocation. • `free(ptr)`: Releases allocated memory back to the heap manager.
Code Example
c
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5;
int *arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
return 1;
}
for (int i = 0; i < n; i++) arr[i] = i * 10;
free(arr); // Prevent memory leak
arr = NULL; // Prevent dangling pointer use
return 0;
}How It Works & Key Takeaways
Always check for `NULL` after `malloc`, and set freed pointers to `NULL` to avoid dangerous use-after-free bugs.
Mock Test · 1 Questions · Optional
Ready for File I/O?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate3 questions