C
ASLR
Learn address space layout randomization with ASLR.
What is ASLR?
ASLR (Address Space Layout Randomization) randomizes the location of memory regions every time a program runs. Code, stack, heap and libraries land at different addresses.
Even if an attacker finds a bug, they cannot know the target address in advance, so the attack fails. On Linux it is controlled by /proc/sys/kernel/randomize_va_space: 0 off, 1 partial, 2 full. The compiler's -fPIE option makes the program position independent, which ASLR needs to fully apply. ASLR is not enough alone; it works with canaries and safe functions.
PIE and ASLR interaction
PIE (Position Independent Executable) lets the program code be loaded at any address. Without PIE, ASLR only randomizes stack and heap; the code segment stays fixed.
The compiler builds with -fPIE, the linker links with -pie. Together they place the program itself at a random address. Attackers can no longer know gadget addresses inside the code, which makes ROP attacks harder. Production builds turn PIE on by default. Still, the main defense is not writing bugs in the first place: avoid functions that skip bounds checks.
Exercise Print memory region info
Define void print_aslr_info(const char *region, int base) with body printf("%s=%d\n", region, base);. In main call it for three regions: ("text", 4194304), ("stack", 65536), ("heap", 1048576).
Show example solution
#include <stdio.h>
void print_aslr_info(const char *region, int base) {
printf("%s=%d\n", region, base);
}
int main(void) {
print_aslr_info("text", 4194304);
print_aslr_info("stack", 65536);
print_aslr_info("heap", 1048576);
return 0;
}
Test yourself
-
Complete the ASLR status message
printf("ASLR: %s
", enabled ? "ON" : "____");
Show answer
printf("ASLR: %s
", enabled ? "ON" : "OFF");
-
Match memory regions
- text
- Code segment
- stack
- Stack
- heap
- Heap
- library
- Library
-
What does ASLR randomize?
- Memory region locations
- Only dates
- Only file names
- Only user names
Show answer
Memory region locations — ASLR randomizes the addresses of memory regions.
Next lesson: Format string