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";
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.