04-21-2010
23,310,
4,623
Join Date: Aug 2005
Last Activity: 7 July 2020, 11:47 AM EDT
Location: Saskatchewan
Posts: 23,310
Thanks Given: 1,331
Thanked 4,623 Times in 4,217 Posts
This will find the top of the page of memory the variable's in, assuming a system where pages are 4096 bytes(not always a good assumption!) but won't actually find the top of the stack unless you're within 4096 bytes of it. If you calculate it from inside main(), this is possible if you don't have too many local variables. If you're in linux, you can find the top of the stack more reliably by reading /proc/self/maps, which is a human-readable file listing memory segments for a process one segment per line. The one labelled [stack] is what you want.
Because memory's divided into chunks of fixed size, 4096 on many systems, the stack will always begin at a multiple of the pagesize. Your code works by dividing memory into 4096-byte chunks, which it is on many systems, and subtracting any remainder from it. Remainder works like 4097 % 4096 = 1, 8192 % 4096 = 0, 8193 % 4096 = 1 etc. so you can do pos-=(pos%4096) to rewind the number it to the beginning of a multiple of 4096.
You should use getpagesize() instead of 4096.
Why they're adding 100 to it after all that, I can only guess. They may be calculating the address of something inside the stack rather than the very top of the stack.
Last edited by Corona688; 04-21-2010 at 03:54 PM..