ASLR
- C course
- Expert
- Lesson 21/47
- 5 min
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.
Practice 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).
Starter code
#include <stdio.h>
// Define print_aslr_info function
// Call it for text, stack, heap with (name, base)
int main(void) {
return 0;
}Sample 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;
}Expected output
text=4194304 stack=65536 heap=1048576
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ASLR status message
printf("ASLR: %s
", enabled ? "ON" : "____");
printf("ASLR: %s
", enabled ? "ON" : "OFF");
Explanation: When ASLR is off, "OFF" is printed.
2 Match memory regions
| Term | Meaning |
|---|---|
text |
Code segment |
stack |
Stack |
heap |
Heap |
library |
Library |
3 What does ASLR randomize?
- Memory region locations Correct answer
- Only dates
- Only file names
- Only user names
Explanation: ASLR randomizes the addresses of memory regions.