Pergunta

I have a pointer available with me to a C/C++ variable. Is it possible to exactly make out which segment of the memory this variable belongs to ? If yes, how ?

Note: I just have the address of this variable, no further information if the variable is local/global etc.

Foi útil?

Solução

Find out whether your architecture has pointers to your heap or stack region. Usually there are some stackpointers or framepointers..

Then compare your actual address to those addresses and decide where they belong.

Outras dicas

If you are using linux (not sure about other unices), you might be able to find the information in the file /proc/<pid>/maps

You can first identify what are the beginning and the end of the different sections in your executable. For this, you need to eventually add some variables in the linker script around each sections like this:

SECTIONS {
    [...]
    .data : {
        data_start = .;
        *(.data)
        data_end = .;
    }
    [...]
}

You can then declare these variables as external in your C/C++ code and use them directly to compare the address you want to identify.

It may not be easy to tweak the linker script. With gcc, you can dump it with:

gcc -Wl,-verbose whatever.c

then try to find variables already defined in the (messy) output.

To get the boundaries of the stack, you may instantiate a dummy variable at the beginning of your main() function, and save its address as the top of the stack, then instantiate another one at the current position, which will give you the bottom. However, note that the compiler may not behave exactly like this (stack order of the variables in C is not guaranteed, not even the use of the stack) so this should work but not be portable.

Finally, for the heap, I have no trick. I would just infer that a variable not in data/bss/derivated and not in the stack would be in the heap (excluding registers, but if you can get the address, I would bet that the compiler will never use a register-only storage).

I don't know exactly if it fits your situation, but you can try objdump -t to see the symbol table of an elf file . All you need is the address of your variable. There you can find flags which show you the section for each variable. Refer to man page for objdump for more details.

Sample output :

0804a020 g     O .bss   00000004              var

It says var is a global Object in address 0804a020, section .bss

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top