6.5Dynamic memory: malloc, free, leaks and dangling pointers
The idea
malloc gives you heap memory that you must free. Losing the last pointer to a block is a leak; using a block after its owner is gone is a dangling pointer.
Think of it like this: Renting a storage unit: if you lose the key you keep paying (leak); if you keep using the unit after the lease ends, someone else's stuff is there (dangling).
Why it exists
GATE asks which problem a short malloc snippet suffers from.
How it works
- p = malloc(n) returns the block's address (or NULL).
- free(p) returns it; do not use p afterwards, and never free twice.
- If p is overwritten before free, no pointer to the block remains: a leak.
- Returning &local gives a pointer into a dead stack frame: dangling.
Worked example: x = malloc; x = assignval(x, 0); … x = malloc(…)
The first block was only reachable through x. When x is reassigned to a second malloc, the first block is lost: memory leak. The program still compiles and runs.
Now play with it
- →Run memory leak and look at the heap panel: two blocks allocated, only one freed.
- →Open dangling pointer and read the explanation.
The heap block appears when malloc runs and is marked freed after free(p).
1#include <stdio.h>2int main() {3 int *p = malloc(sizeof(int));4 *p = 42;5 printf("%d\n", *p);6 free(p);7 return 0;8}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
Which describes int *p = malloc(4); p = NULL;?
Exam notes (the dense version)
malloc(n) returns n bytes of heap memory (or NULL) that you must free. Memory leak: you lose the only pointer to a block (for example by overwriting it) before freeing it. Dangling pointer: you use a pointer after free, or after the stack frame it points into has been popped. Double free and writing past the block are undefined behaviour. malloc needs no cast in C.
Previous year questions: Storage Classes, Scope & Memory (8)
PYQs are grouped by topic, so this is the full set for Storage Classes, Scope & Memory; try the ones that match this subtopic. Open all 8 on the topic page.