
Memory Management in C
? Memory Management in C
Memory management in C is all about allocating, accessing, and freeing memory manually. Unlike modern languages with garbage collection, you control everything in C — which gives you both power and responsibility. ???
? Types of Memory in C
? calloc
vs malloc
int *a = (int *)malloc(5 * sizeof(int)); // Uninitializedint *b = (int *)calloc(5, sizeof(int)); // All set to 0
? realloc
Example
int *arr = malloc(2 * sizeof(int));arr = realloc(arr, 4 * sizeof(int)); // Resize to hold 4 ints
?? Common Mistakes to Avoid
? Forgetting to
free()
? memory leak? Accessing freed memory ? undefined behavior
? Dereferencing null or uninitialized pointers
? Always check if
malloc
/calloc
returnsNULL
? Tip: Always Pair
malloc ? free calloc ? free realloc ? free