Memory Management
advancedPart of Advanced C
Theory
C gives the programmer direct control over memory. Understanding stack vs heap, the malloc/calloc/realloc/free functions, and memory leak prevention is essential for writing robust C programs.
Stack vs Heap
| Feature | Stack | Heap | |---------|-------|------| | Allocation | Automatic (function calls) | Manual (malloc/free) | | Speed | Very fast | Slower | | Size | Limited (typically ~8 MB) | Large (RAM limit) | | Lifetime | Function scope | Until explicitly freed | | Management | Compiler handles it | Programmer handles it |
Dynamic Memory Functions
malloc(size)— allocatessizebytes, returns uninitialized memorycalloc(n, size)— allocatesnelements ofsizebytes each, zero-initializedrealloc(ptr, newSize)— resizes previously allocated memoryfree(ptr)— deallocates memory, preventing leaks
Best Practices
Always check if malloc/calloc returns NULL. Always pair every allocation with a free(). After freeing, set the pointer to NULL to prevent dangling pointers.
Practical Examples
Exercises
Dynamic Student Grades
Write a C program that asks the user for the number of students, dynamically allocates an array of that size using malloc(), reads grades into the array, calculates the average, and frees the memory.
Starter Code:
#include <stdio.h>\n#include <stdlib.h>\n\nint main() {\n int n;\n // Your code here\n return 0;\n}Expected Output:
Enter number of students: 3\nEnter grade 1: 85\nEnter grade 2: 90\nEnter grade 3: 78\nAverage: 84.33