-2

When running several times the same C programm, the address returned by malloc is always different. Is it possible to force Linux/gcc to always get the same adresses for a memory allocation ?

Thanks, Fred

Fred
  • 39
  • 4
  • 2
    Why do you care what address is returned? – Barmar Sep 05 '17 at 15:27
  • 2
    Why does it need to, out of interest? – Bathsheba Sep 05 '17 at 15:27
  • 1
    See https://en.wikipedia.org/wiki/Address_space_layout_randomization – Barmar Sep 05 '17 at 15:27
  • 4
    Sounds like a [XY-problem](http://xyproblem.info/), or do you aks just because you are curious? – izlin Sep 05 '17 at 15:29
  • See [this question](https://stackoverflow.com/questions/11238457/disable-and-re-enable-address-space-layout-randomization-only-for-myself) regarding enabling/disabling address space layout randomization on Linux. – dbush Sep 05 '17 at 15:31
  • @dbush if ASLR is disabled, does it guarantee that the first malloc will return the same address on successive runs? – Jabberwocky Sep 05 '17 at 15:33
  • Why do you need this? Even if it's for a test (unit, or any other kind), it really should not depend on the value returned malloc, other than checking if it's other than null (allocation failure). – J_S Sep 05 '17 at 15:34
  • @MichaelWalz I would say no. Some library thread/s in a race to the malloc mutex... and you're back with unreliable repeatability. – Martin James Sep 05 '17 at 15:36
  • BTW, gcc is a compiler. It has nothing to do with returning memory address. – Makketronix Sep 05 '17 at 22:34
  • I have an array of structures, each element has an id and severals pointers and offsets. I had an instability, some runs work fine and other ones failed. I dumped the content of the elements to check the offsets which must be constant from one run to the other. As the pointers always change, the diff is difficult. I agree that a good solution could be to dump only the offsets but I'd like to know if there is a way to make the pointers constant. – Fred Sep 06 '17 at 16:27

1 Answers1

0

The only way to do this is to assign the same address everytime, as in this question. However what you're doing is questionable, and it is most likely the case there's a better way of doing what you want to do, rather than always getting the same address.

Aidan Connelly
  • 164
  • 3
  • 13
  • The same physical address, that is not always the same value the malloc function returns! It's possible to obtain physical addresses using other functions than malloc. – Sir Jo Black Sep 05 '17 at 15:52
  • Some IPC functions may be used to obtain and manage same memory areas between different processes. – Sir Jo Black Sep 05 '17 at 15:57