Linux: Fix the address returned by malloc

In a normal Linux environment, even a program that simply mallocs and displays its address will display a different address each time it is executed.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char* p = malloc(1024);
    printf("p = %p\n", p); 
    return 0;
}

Execution result:

$ a.out
p = 0xdd8fa82010
$ a.out
p = 0xe683097010
$ a.out
p = 0xb79170f010

This is a function called Address space layout randomization in the kernel, which intentionally randomizes addresses for security reasons.

However, there are times when you want to fix the address, such as when debugging. In such a case

$ echo 0 > /proc/sys/kernel/randomize_va_space

And it is sufficient. Values other than 0 are accepted as follows:

0 – No randomization. Everything is static.
1 – Conservative randomization. Shared libraries, stack, mmap(), VDSO and heap are randomized.
2 – Full randomization. In addition to elements listed in the previous point, memory managed through brk() is also randomized.

reference:

kernel - How can I temporarily disable ASLR (Address space layout randomization)? - Ask Ubuntu

Recommended Posts

Linux: Fix the address returned by malloc
Linux: Rename the process displayed by the ps command
Linux: Understand the information displayed by the top command
Linux: Netplan configuration guide to see when you want to fix the IP address
Control the Linux trackpad
About the number (section number) in () displayed by the Linux man command