Stack pointers vs Heap pointers
What you'll learn: You'll learn how to distinguish between pointers that manage temporary local memory and pointers that handle long-term manual memory.
The Automatic vs. The Manual
In C, a pointer is just an address, but where that address points changes everything about how you manage it. Think of the Stack like a post-it note on your desk—it's for quick, temporary scribbles that you throw away as soon as you finish a task. Think of the Heap like a storage unit you rent—you have to sign for it, keep track of the key, and explicitly cancel the lease when you're done.
Stack Pointers: Short-Lived and Automatic
When you declare a pointer that points to a local variable, you are using a stack pointer. You don't need to "create" this memory; it exists as long as the function is running. However, once the function hits its closing brace }, that memory is reclaimed by the system. If you try to use that pointer elsewhere, your program will likely crash because the "post-it note" has been shredded.
Heap Pointers: Long-Term and Manual
When you use malloc(), you get a heap pointer. The system carves out a block of memory that stays reserved for you until you manually call free(). This is powerful because the memory survives even after a function ends, but it is dangerous because if you lose the pointer (the "key" to the storage unit), you can never get that memory back—this is a memory leak.
Seeing the Difference
#include <stdlib.h>
void pointer_demo() {
// 1. A Stack Pointer
int local_var = 42;
int *stack_ptr = &local_var;
// This memory is managed automatically.
// 2. A Heap Pointer
int *heap_ptr = malloc(sizeof(int));
if (heap_ptr != NULL) {
*heap_ptr = 100;
// You must manually clean this up!
free(heap_ptr);
}
}
How to Choose?
If you just need a temporary variable for a calculation, keep it on the stack. It's faster and safer. If you need data to stay alive across many different functions, or if you don't know how much data you'll have until the program is running, use a heap pointer.
Key takeaway
Stack pointers point to temporary memory that cleans itself up, while heap pointers point to memory that you must manually create and destroy.