01. Heap Allocation with malloc(), calloc() & free()
🟡 Difficulty: Intermediate | Dynamic Heap Storage, Zero-Initialization & Deallocation
📖 Definition
Dynamic memory allocation enables C programs to request RAM memory blocks from the system Heap Segment during runtime execution. The malloc() function allocates uninitialized raw bytes, calloc() allocates zero-initialized memory, and free() releases heap memory back to the operating system.
🎯 Why It Is Used
- Runtime Sizing: Allocating data structures whose sizes are determined by user input or file content at runtime.
- Persistent Dynamic Data: Creating heap data structures (like linked lists, trees, hash tables) that outlive individual function stack frame calls.
⚙️ How It Works: Stack vs Heap Architecture
| Property | Stack Memory Segment | Heap Memory Segment |
|---|---|---|
| Allocation Method | Automatic (Function invocation) | Manual (malloc / calloc) |
| Lifetime | Function Scope (Destroyed on return) | Manual (Persists until free()) |
| Typical Capacity Limit | Small (1 MB – 8 MB) | Large (Gigabytes / Total System RAM) |
| Deallocation Risk | None (Handled by CPU SP register) | Memory Leak if free() is omitted! |
📝 Syntax
#include <stdlib.h>
// 1. malloc: Allocates 'count * sizeof(type)' bytes (Uninitialized Garbage Data!)
int *arr1 = (int*)malloc(count * sizeof(int));
// 2. calloc: Allocates AND ZERO-FILLS 'count' elements of 'sizeof(type)'
int *arr2 = (int*)calloc(count, sizeof(int));
// 3. Mandatory NULL Check before dereferencing!
if (arr1 == NULL || arr2 == NULL) {
// Allocation failed! Handle out-of-memory error
}
// 4. Deallocation
free(arr1); arr1 = NULL;
free(arr2); arr2 = NULL;
🔀 Casting malloc() Return Values in C vs C++
In ISO C, malloc() returns a generic void* pointer that converts implicitly to any typed pointer (e.g. int *p = malloc(...);). In C++, explicit casting (int *p = (int*)malloc(...);) is mandatory. Using explicit casts in C maintains cross-compiler compatibility with C++.
🌱 Beginner Example: Dynamic Integer Array with malloc()
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t count = 5;
// Allocate array of 5 integers on heap
int *numbers = (int*)malloc(count * sizeof(int));
if (numbers == NULL) {
fprintf(stderr, "Fatal Error: Heap allocation failed!\n");
return 1;
}
// Populate and print heap array
for (size_t i = 0; i < count; i++) {
numbers[i] = (int)(i + 1) * 10;
printf("numbers[%zu] = %d\n", i, numbers[i]);
}
// Free heap memory AND nullify pointer
free(numbers);
numbers = NULL;
return 0;
}
🌼 Intermediate Example: Zero-Initialized Array with calloc()
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t count = 4;
// calloc zero-initializes all bytes automatically!
int *zeros = (int*)calloc(count, sizeof(int));
if (zeros == NULL) return 1;
printf("=== Verifying calloc Zero-Initialization ===\n");
for (size_t i = 0; i < count; i++) {
printf("zeros[%zu] = %d (Guaranteed 0!)\n", i, zeros[i]);
}
free(zeros);
zeros = NULL;
return 0;
}
🌲 Advanced Example: Dynamic Struct Array Allocation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int id;
char name[32];
double salary;
} Employee;
int main(void) {
size_t emp_count = 2;
Employee *team = (Employee*)malloc(emp_count * sizeof(Employee));
if (team == NULL) return 1;
// Initialize Employee 1
team[0].id = 101;
snprintf(team[0].name, sizeof(team[0].name), "Alice Smith");
team[0].salary = 95000.0;
// Initialize Employee 2
team[1].id = 102;
snprintf(team[1].name, sizeof(team[1].name), "Bob Jones");
team[1].salary = 88000.0;
printf("=== Heap Employee Database ===\n");
for (size_t i = 0; i < emp_count; i++) {
printf("ID: %d | Name: %-12s | Salary: $%.2lf\n",
team[i].id, team[i].name, team[i].salary);
}
free(team);
team = NULL;
return 0;
}
🔍 Line-by-Line Explanation
int *numbers = (int*)malloc(count * sizeof(int));: Requests a contiguous 20-byte block on the heap.if (numbers == NULL): Verifies that the operating system successfully granted the heap allocation request.free(numbers); numbers = NULL;: Releases the 20-byte heap block and nullifies the pointer to prevent dangling pointer bugs.
💻 Expected Terminal Output
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
=== Verifying calloc Zero-Initialization ===
zeros[0] = 0 (Guaranteed 0!)
zeros[1] = 0 (Guaranteed 0!)
zeros[2] = 0 (Guaranteed 0!)
zeros[3] = 0 (Guaranteed 0!)
=== Heap Employee Database ===
ID: 101 | Name: Alice Smith | Salary: $95000.00
ID: 102 | Name: Bob Jones | Salary: $88000.00
⚠️ Common Mistakes & Pitfalls
- Forgetting NULL Check: Dereferencing
numbers[0]without checkingif (numbers == NULL)crashes if system memory is exhausted. - Double Free Bug: Calling
free(p); free(p);on the same pointer triggers heap corruption crashes. Setp = NULL;after freeing! - Memory Leak: Failing to call
free()on allocated heap memory leads to memory leaks that exhaust system RAM.
📌 Important Rules & Limitations
- Always check if heap allocation functions return
NULLbefore using memory. - Every
malloc/calloccall must have a correspondingfree()call. - Set pointers to
NULLimmediately after freeing.
🌐 Multilingual Explanation: English
malloc() allocates uninitialized heap memory; calloc() allocates zeroed memory. Always check for NULL and release memory using free() to prevent memory leaks.
🌐 Multilingual Explanation: Hindi (Roman Script)
malloc() heap par memory allocate karta hai, aur calloc() memory allocate karke use zero-fill kar deta hai. Memory use hone ke baad free() karna zaroori hai.
🌐 Multilingual Explanation: Marathi (Roman Script)
malloc() heap var memory allocate karto aani calloc() zeroed memory deto. Work purna jhalyavar free() vapra.
❓ Practice Questions
- What is the primary difference between
malloc()andcalloc()? - Why is it critical to check if
malloc()returnsNULL? - What happens if you call
free()twice on the same pointer?
🚀 Practical Coding Challenge
Write a C program named dynamic_array_sum.c that prompts the user for N, allocates an integer array of size N using calloc, prompts for N values, computes their sum, and frees the memory.
🧭 Navigation & Breadcrumbs
← Module 12 Guide | Next: 02. Dynamic Resizing with realloc() →