C Memory Management
In this page:
What is Memory Management?
Memory management in C is the process of allocating space for data as a program needs it and releasing that space when it's no longer needed, a responsibility the programmer handles manually rather than an automatic garbage collector.
Example: What is Memory Management?
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
printf("%d", *ptr);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Stack vs Heap Memory
C programs use two main regions of memory: the stack, which automatically manages local variables tied to function calls, and the heap, a pool of memory that must be explicitly allocated and freed by the programmer.
Example: Stack vs Heap Memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int stackVar = 5;
int *heapVar = malloc(sizeof(int));
*heapVar = 10;
printf("%d %d", stackVar, *heapVar);
free(heapVar);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Static vs Dynamic Allocation
Static allocation, like a regular array declaration, fixes memory size at compile time, while dynamic allocation, using functions like malloc, lets a program decide how much memory it needs while it's actually running.
Example: Static vs Dynamic Allocation
#include <stdio.h>
#include <stdlib.h>
int main() {
int staticArr[5];
int *dynamicArr = malloc(5 * sizeof(int));
printf("%zu %d", sizeof(staticArr), dynamicArr != NULL);
free(dynamicArr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Allocate-Use-Free Lifecycle
Every block of dynamically allocated memory follows a lifecycle: it's allocated with a function like malloc, used through a pointer, and then released exactly once with free when it's no longer needed.
Example: The Allocate-Use-Free Lifecycle
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 42;
printf("%d", *ptr);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Common Memory Management Mistakes
The most common memory management mistakes are memory leaks, where allocated memory is never freed, and use-after-free, where a pointer is dereferenced after its memory has already been released, both of which lead to serious bugs.
Example: Common Memory Management Mistakes
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
free(ptr);
ptr = NULL;
printf("%d", ptr == NULL);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: