LoginSignup
11

More than 5 years have passed since last update.

Linux: mallocで返されるアドレスを固定する

Posted at

通常のLinux環境では、単純にmallocしてそのアドレスを表示するだけのプログラムでも、実行するたびに異なるアドレスが表示される。

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

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

実行結果:

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

これはカーネルのAddress space layout randomizationという機能で、セキュリティ上の理由により意図的にアドレスをランダム化している。

しかしデバッグ時など、アドレスを固定化したい場合もある。そのようなときは

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

とすればよい。
0以外に受け付ける値は下記の通り:

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.

参考:

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11