c - How to find address of a function without using any pointer or & -
i asked in interview find out address of function without using pointer or &. couldn't reply question when checked him answer, has given next illustration in function f1() calls function f2(). so, when function f2() gets invoked, stack stores homecoming address nil address of function f1(). in function f2() can read stack , find out address stored in stack of function f1(). can 1 explain in detail how can read stack function f2() , find out address of f1().
int main() { f1(); homecoming 0; } void f1() { f2(); }
with caveat method utterly unportable t.c. mentions, , additional caveat not work if optimizations turned on, can read homecoming address stack reading off end of buffer, in illustration below.
int main() { f1(); homecoming 0; } void f1() { f2(); } void f2() { char buf[4]; printf("%p\n", *(void**)(buf + 8)); } note number 8 above vary based on operating system, architecture, , compiler padding, have seek variety of different numbers create work. selection of 8 illustration assumes padding 4-byte boundary, , 4-byte pointers on 32-bit system.
you have create sure optimizations turned off.
the reason why works @ because construction of stack after function phone call looks kind of this.
|return address| |saved frame pointer| |local variables| observe homecoming address @ higher address local variables. reason reading past end of buffer allow potentially read homecoming address.
the reason why breaks optimizations compiler might decide inline 1 or both functions, or realize 1 of them doing nil @ , optimize function phone call away entirely, blows aside assumptions stack.
c
No comments:
Post a Comment