Reputation: 5296
If I store a pointer to a function, and then at some later point during my program's execution, compare it to the address of the same function, are the two addresses guaranteed to be equal.
E.g.
int foo(void){return 0;}
int (*foo_p)(void) = &foo;
assert(foo_p == &foo);
In the above code is the assertion always guaranteed to succeed? Are there any circumstances under which the address of a function can change?
Upvotes: 12
Views: 531
Reputation: 794
A function's address will never change. Many programs are built around the concept of callbacks, which would not work if a function's address could change.
If, hypothetically, a function's location changed, for example by a self-modifying program, then all calls to that function would cause a segfault or very undefined behaviour any way. Edit: Clarification - function symbols are like pointers, if you free
memory pointed to by a pointer, that will not zero the actual pointer variable, it will still point there, just as your function calls will still point to the old location of the moved function.
Self-modifying programs are very big exceptions though, and in these days the code section of a binary is write protected rendering this very, very hard.
Upvotes: 0
Reputation: 215261
Per 6.5.9:
Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.
(Boldface added for emphasis.)
Upvotes: 17