C
Beginner
1 min read
Stack vs Heap Memory
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* BUG: returns pointer to local stack variable */
/* DO NOT do this in real code! */
int *bad_return(void)
{
int local = 42;
return &local; /* dangling pointer — undefined behaviour */
}
/* CORRECT: allocate on heap so it outlives the function */
int *good_return(int value)
{
int *p = malloc(sizeof(int));
if (p) *p = value;
return p;
}
/* CORRECT: caller provides storage */
void fill_values(int *out, int n)
{
for (int i = 0; i < n; i++) out[i] = i * 10;
}
int main(void)
{
/* Stack allocation — automatic lifetime */
int stack_arr[8];
fill_values(stack_arr, 8);
printf("Stack: %d %d %d\n", stack_arr[0], stack_arr[1], stack_arr[2]);
/* Heap allocation — manual lifetime */
int *heap_arr = malloc(8 * sizeof(int));
if (!heap_arr) { perror("malloc"); return EXIT_FAILURE; }
fill_values(heap_arr, 8);
printf("Heap: %d %d %d\n", heap_arr[0], heap_arr[1], heap_arr[2]);
free(heap_arr);
/* Heap scalar */
int *hp = good_return(99);
if (hp) {
printf("Heap int: %d\n", *hp);
free(hp);
}
printf("sizeof stack_arr: %zu bytes\n", sizeof(stack_arr));
return 0;
}