Challenges/Memory & Types/Stack vs Heap Address Comparison

Stack vs Heap Address Comparison

๐Ÿ”ด Hard

Stack vs Heap Address Comparison

Implement `is_on_heap` that takes a pointer and returns 1 if it was allocated with `malloc`, 0 if it's a stack variable.

Strategy: Compare the pointer address to a known stack address. Heap allocations are at higher or lower addresses than the stack depending on the architecture.

Also implement `print_memory_layout` that prints the addresses of: a local variable, a static variable, a global variable, and a heap allocation.

Why it matters: Understanding where your data lives is critical when writing bootloaders, RTOS tasks with separate stacks, or debugging stack overflows.

Test Cases

1.
heap pointer returns 1
is_on_heap(malloc(4)) == 1
2.
stack pointer returns 0
int x; is_on_heap(&x) == 0
3.
global returns 0
is_on_heap(&global_var) == 0
solution.c
Prev
6 of 6 ยท Memory & Types
All modules