Possible to know section of memory a variable is located?

前端 未结 2 1619
情书的邮戳
情书的邮戳 2021-01-22 14:36

Is there any way in a C program to know the section that a variable is in? For example:

char*   str     = "Word1";
char    str2[]  = "Word2";
         


        
2条回答
  •  一整个雨季
    2021-01-22 15:22

    It is not possible for a C program to know the section that its variable is in with absolute certainty. It is just like the Heisenberg uncertainty principle - the mere act of taking the address of a variable can make it to exist in memory, when it could otherwise be eliminated completely by optimization.

    Thus use readelf or gdb or objdump, they're decoding the actual executable.

    In principle the ELF headers should be loaded in memory and you can deduce the sections from it, and you could read /proc/xx/maps on Linux and all such, but... unless actually attempting to write a debugger, a garbage collector or such, I wouldn't bother.

提交回复
热议问题