Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

c++ - disable the randomness in malloc

I'm running this following simple C program:

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

int main(int argc, char** argv){
  void *p = malloc(4);
  fprintf (stderr, "p==%p
", p);
  return 0;
}

Different runs give different results:

p==0x101c010

then: p==0x1ad9010

then: p==0xe77010

and so.

As I remember, in the past malloc was fully deterministic. So probably from some version, some randomness was added to malloc. I am using now gcc-4.6.3 on Ubuntu.

Is there a way to eliminite that randomness ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the variation is caused by address space layout randomization, then, according to this page, you can disable it with:

echo 0 | sudo tee /proc/sys/kernel/randomize_va_space

This should be done only temporarily for debugging purposes.

This is a good paper on interposing functions: Intercepting Arbitrary Functions on Windows, UNIX, and Macintosh OS X Platforms by Daniel S. Myers and Adam L. Bazinet. This would allow you to replace the malloc behavior with a completely controlled implementation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...