Sub topic 14
Memory leaks, dangling pointers, and undefined behavior
This chapter assumes you can use malloc and free, know that a pointer holds an address, and understand that local variables live in a stack frame that disappears when the function returns. It covers the ways heap and pointer code goes wrong, and which of those ways the C standard defines.
Undefined behavior
Undefined behavior (UB) means the standard places no requirements on what the program does. It may print the "expected" value, crash, print garbage, or behave differently after you change the optimization level. Compilers assume UB never happens and optimize on that assumption. A program that "worked when I ran it" can still contain UB.
For GATE, the rule is: if a snippet reaches UB, no single output is guaranteed. The correct option is usually "undefined" or "compiler dependent", not whatever your compiler printed.
A memory leak is different. A leak is well-defined behavior that wastes memory.
| Problem | Defined by the standard? | Typical effect |
|---|---|---|
| Memory leak | Yes | Heap usage grows, nothing crashes immediately |
| Use after `free` | No, UB | Stale data, corruption, or a crash |
| Returning the address of a local | No, UB when the pointer is used | Garbage once the frame is reused |
| Double `free` | No, UB | Heap corruption, often an abort |
| `free(NULL)` | Yes, does nothing | None |
| Dereferencing `NULL` | No, UB | Usually a segmentation fault |
| Reading an uninitialized local | No, indeterminate value | Garbage |
| Out-of-bounds array access | No, UB | Corruption or a crash |
| Signed integer overflow | No, UB | Unpredictable after optimization |
| Unsigned overflow | Yes, wraps modulo 2^N | Wraps around |
Memory leaks
A leak happens when a heap block is still allocated but no pointer to it remains, so it can never be freed. The most common cause is overwriting the only pointer.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *p = malloc(100 * sizeof *p);
if (p == NULL) {
return 1;
}
p[0] = 7;
p = malloc(50 * sizeof *p); /* the first block is now unreachable: leak */
if (p == NULL) {
return 1;
}
printf("%d\n", p[0] == 7); /* reading uninitialized heap memory: indeterminate */
free(p); /* frees only the second block */
return 0;
}Other leak sources are returning early from a function without freeing, forgetting to free every node of a list, and freeing a struct without first freeing the blocks it points to. The fix is to give each allocation exactly one owner and one matching free. Free the owned inner blocks before the outer one.
Dangling pointers
A dangling pointer holds an address whose object no longer exists. There are three usual sources.
- Use after free. After
free(p), the pointer keeps its old value, but the block belongs to the allocator again. - Returning the address of a local. The variable dies when its frame is popped, so the caller receives an address into dead stack space.
- A stale copy after
realloc.reallocmay move the block. Every other pointer to the old block then dangles.
int *bad(void) {
int x = 5;
return &x; /* the pointer is returned, but x is gone; using it is UB */
}The correct versions allocate on the heap, or have the caller supply the storage. Setting a pointer to NULL after freeing it also prevents a double free, because free(NULL) does nothing.
#include <stdio.h>
#include <stdlib.h>
int *make_value(void) {
int *p = malloc(sizeof *p);
if (p != NULL) {
*p = 42;
}
return p;
}
int main(void) {
int *p = make_value();
if (p == NULL) {
return 1;
}
printf("%d\n", *p);
free(p);
p = NULL;
free(p); /* defined: free(NULL) does nothing */
return 0;
}This prints 42.
Using realloc safely
Writing a = realloc(a, n) loses the original block if realloc returns NULL, which leaks it. Assign the result to a temporary first.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = malloc(10 * sizeof *a);
if (a == NULL) {
return 1;
}
for (int i = 0; i < 10; i++) {
a[i] = i;
}
int *tmp = realloc(a, 20 * sizeof *a);
if (tmp == NULL) {
free(a); /* the old block is still valid and still ours */
return 1;
}
a = tmp; /* never use the old value of a after a successful move */
printf("%d\n", a[9]);
free(a);
return 0;
}This prints 9. After a successful realloc, the first 10 elements are preserved. The new elements are uninitialized.
Lifecycle of a heap block
A block moves through a small set of states. Any operation not shown on an arrow, such as reading after the block is freed, is UB.
Other undefined behavior in GATE questions
- Out-of-bounds access.
int a[5]; a[5] = 1;is UB. Forming the pointera + 5(one past the end) is legal, but dereferencing it is not. - Uninitialized variables. A local
int x;has an indeterminate value. Globals andstaticvariables are zero-initialized. - Unsequenced modification.
i = i++;anda[i] = i++;modify and read the same object without a defined order, so they are UB. The same applies toi++ + i++. Function argument evaluation order is unspecified, sof(i++, i++)can produce different results on different compilers. - Signed overflow.
INT_MAX + 1is UB, whileUINT_MAX + 1uis0. - Invalid
free. Passingfreea pointer that did not come frommalloc,calloc, orrealloc, or one that points into the middle of a block, is UB. - Pointer subtraction across objects. Subtracting pointers into different arrays is UB.
Habits that prevent these errors
- Check every allocation result for
NULLbefore using it. - Pair each
mallocwith onefree, and decide which function owns the block. - Set a pointer to
NULLright after freeing it. - Use
sizeof *pinstead ofsizeof(type), so the size follows the pointer's type. - Never keep two owning pointers to the same block.
Tools such as Valgrind and AddressSanitizer (-fsanitize=address) detect leaks, use after free, and out-of-bounds access at run time.
Exercise
A function declares int arr[3] = {1, 2, 3}; and returns arr. The caller prints *p from the returned pointer. Is this a memory leak, a dangling pointer, or defined behavior? Name a fix.
Show answer
It is a dangling pointer. The array is a local, so it is destroyed when the function returns, and the caller's read is undefined behavior. Fixes: allocate the array with malloc and have the caller free it, make the array static, or have the caller pass in an array to fill.
Exercise
In int *p = malloc(sizeof *p); *p = 1; free(p); free(p);, which line first causes undefined behavior, and why would p = NULL; after the first free have made the program legal?
Show answer
The second free(p) is the first UB, because the block was already released (a double free). After p = NULL;, the second call becomes free(NULL), which the standard defines as doing nothing.