Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the end address of a function in a C prog?

Tags:

c

Start address can be obtained from the function name, how to find the end address of a function? I have been asked this question in interview:

Consider the function f() which i wrote has crossed the text section and started over writing the adjacent section (data section). How can i handle this situation? Also he added that i should handle it through C code. I should not see the symbol map file and get the address.

like image 340
vijayanand1231 Avatar asked Jun 18 '12 15:06

vijayanand1231


People also ask

How do you find a function address?

We can get the address of a function by just writing the function's name without parentheses. Please refer function pointer in C for details. In C/C++, name of a function can be used to find address of function.

How do you print the address of a function in C?

Without using the separate pointer for print the address of the function, You can use the name of the function in the printf . printf("The address of the function is =%p\n",test); For printing the address in the hexa-decimal format you can use the %p .

Where is function address stored in C?

Address of a function in C or C++ In C or C++, the variables are stored into memory, so we can get their memory addresses. Similarly, the functions also are stored into the memory, so they also have some addresses.

Where are function addresses stored?

To point to data, pointers are used. Like normal data pointers, we have function pointers that point to functions . The address of a function is stored in a function pointer.


2 Answers

With GCC, you can take the address of a label, with the && operator (yes - &&, not &).
This can be used as follows:

void f(void) {
    printf("Start %p End %p\n", f, &&f_end);
    f_end: return;
}

This won't give you exactly the end, because there's some epilogue code after the label, but I think it's good enough for an interview answer.

like image 71
ugoren Avatar answered Sep 28 '22 02:09

ugoren


The C standard does not guarantee that there is such a thing as then end address of a function.

In practice, functions are not necessarily a single continuous piece of memory, but can overlap, or be fragmented across several pieces by code optimisers.

For that reason there is no way to find this out at runtime.

Furthermore, there is no guarantee that the "start address" you get from GetProcAddress or by taking the address of the function (for a function pointer) bears any relation to where the code actually is.

All a function pointer guarantees is that if you call through the address the function will be executed. It does not guarantee that the code actually resides there. It may just be the address of a thunk, for example.

like image 30
Ben Avatar answered Sep 28 '22 01:09

Ben