Why does setting a variable to its own address give different results for different program runs?

Yesterday I can through this confusing C code that implements Conway Game of Life . As a pseudo-random generator, it writes code for this:

int pseudoRand = (int) &pseudoRand; 

In accordance with the author comments on the program :

This is a large number that should be different for each run, so it works great as a seed.

I'm pretty sure that the behavior here is either defined in the implementation, or undefined. However, I'm not sure why this value will differ from run to run. My understanding of how most OSs work, because of virtual memory, the stack is initialized to the same virtual address every time the program starts, so every time the address should be the same.

Will this code produce different results in different scenarios on most operating systems? Does it depend on the OS? If so, why does the OS map the same program to different virtual addresses each time it starts?

Thanks!

+6
source share
1 answer

While the assignment of addresses to objects with automatic storage is not specified (and the conversion of the address to an integer is determined by the implementation), what you do in your case simply steals the entropy assigned by the kernel to the first stack address as part of the randomization of address space allocation (ASLR) . It is a good idea to use this as a source of entropy that can leak from your program, especially in applications interacting over the network with unreliable, possibly malicious, remote nodes, because you are essentially revealing a random address base that the kernel gave you that you might want to know about this and thereby defeat the goal of ASLR. (Even if you just use it as a seed, if the attacker knows the PRNG algorithm, they can cancel it to get the seed.)

+3
source

Source: https://habr.com/ru/post/959093/


All Articles