From inside a Linux process, one could read from /proc/self/maps
to see a description of its address space. For example,
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
void print_maps() {
int fd = open("/proc/self/maps", O_RDONLY);
char buf[512];
int rc;
fflush(stdout); //Not necessary for this example, but I usually
//include before directly writing to STDOUT_FILENO
while ((rc = read(fd, buf, sizeof(buf))) > 0) {
write(STDOUT_FILENO, buf, rc);
}
close(fd);
}
int main(void) {
print_maps();
return 0;
}
For me this prints (I ran this on repl.it):
559de76b2000-559de76b3000 r-xp 00000000 00:12bf 411 /home/runner/crt/main
559de78b2000-559de78b3000 r--p 00000000 00:12bf 411 /home/runner/crt/main
559de78b3000-559de78b4000 rw-p 00001000 00:12bf 411 /home/runner/crt/main
7f259008a000-7f2590271000 r-xp 00000000 08:01 4133143 /lib/x86_64-linux-gnu/libc-2.27.so
7f2590271000-7f2590471000 ---p 001e7000 08:01 4133143 /lib/x86_64-linux-gnu/libc-2.27.so
7f2590471000-7f2590475000 r--p 001e7000 08:01 4133143 /lib/x86_64-linux-gnu/libc-2.27.so
7f2590475000-7f2590477000 rw-p 001eb000 08:01 4133143 /lib/x86_64-linux-gnu/libc-2.27.so
7f2590477000-7f259047b000 rw-p 00000000 00:00 0
7f259047b000-7f25904a4000 r-xp 00000000 08:01 4133125 /lib/x86_64-linux-gnu/ld-2.27.so
7f25906a2000-7f25906a4000 rw-p 00000000 00:00 0
7f25906a4000-7f25906a5000 r--p 00029000 08:01 4133125 /lib/x86_64-linux-gnu/ld-2.27.so
7f25906a5000-7f25906a6000 rw-p 0002a000 08:01 4133125 /lib/x86_64-linux-gnu/ld-2.27.so
7f25906a6000-7f25906a7000 rw-p 00000000 00:00 0
7ffc92553000-7ffc92574000 rw-p 00000000 00:00 0 [stack]
7ffc925f4000-7ffc925f7000 r--p 00000000 00:00 0 [vvar]
7ffc925f7000-7ffc925f8000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
In theory, you could parse this text and have a way of knowing what virtual addresses are free. But is this maps file complete? Is there a more idiomatic way of asking the Linux kernel to indicate some free region in your own virtual address space?