← Back to C Course | Chapter 9: Memory Management | Lesson 1 of 8

C Memory Management

Memory management in C is the process of manually allocating memory as it's needed and releasing it when it's no longer needed, following an allocate-use-free lifecycle to avoid leaks and undefined behavior.

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?

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *ptr = malloc(sizeof(int));
	*ptr = 5;
	printf("%d", *ptr);
	free(ptr);
	return 0;
}

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

c
#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;
}

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

c
#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;
}

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

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *ptr = malloc(sizeof(int));
	*ptr = 42;
	printf("%d", *ptr);
	free(ptr);
	return 0;
}

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

c
#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;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.