ASLR, or Address Space Layout Randomization, is a security measure that changes where a process’s memory regions are placed on each run. This makes attacks that depend on fixed addresses harder. Linux applies ASLR to the stack, which we can observe by locating a local variable in /proc/self/maps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <stdint.h>
#include <stdio.h>

int main(void) {
char marker;
uintptr_t stack_address = (uintptr_t)&marker;

FILE* maps = fopen("/proc/self/maps", "r");
if (maps == NULL) {
perror("fopen");
return 1;
}

unsigned long start, end;
char line[256];

while (fgets(line, sizeof(line), maps) != NULL) {
if (sscanf(line, "%lx-%lx", &start, &end) == 2 &&
start <= stack_address && stack_address < end) {
unsigned long size = end - start;
printf("stack: [0x%lx, 0x%lx], size: %lu KiB\n",
start, end, size / 1024);
fclose(maps);
return 0;
}
}

fclose(maps);
fputs("stack mapping not found\n", stderr);
return 1;
}

Compile it and run it a few times:

1
2
clang stack_aslr.c -o stack_aslr
repeat 3 ./stack_aslr

Example output:

1
2
3
stack: [0x7ffc9b704000, 0x7ffc9b726000], size: 136 KiB
stack: [0x7ffd56d9e000, 0x7ffd56dc0000], size: 136 KiB
stack: [0x7ffc30977000, 0x7ffc30999000], size: 136 KiB