Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C functions guaranteed to have a fixed memory address?

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?

like image 638
j b Avatar asked Sep 08 '11 14:09

j b


People also ask

Do functions have addresses in C?

Address of a function in C or C++ We all know that code of every function resides in memory and so every function has an address like all others variables in the program. We can get the address of a function by just writing the function's name without parentheses.

Do memory addresses change?

Yes, they will change. Write a program that outputs the memory address of a few variables and run it a few times.

What is the address of a function C?

The address is the memory location where the entity is stored. Every block of code in the program has its own memory location in the program. Which means like any variable or object methods and functions also have memory address.

Can we get address of memory by using the function pointer in C?

As we know that we can create a pointer of any data type such as int, char, float, we can also create a pointer pointing to a function. The code of a function always resides in memory, which means that the function has some address. We can get the address of memory by using the function pointer.


1 Answers

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.)

like image 172
R.. GitHub STOP HELPING ICE Avatar answered Nov 09 '22 22:11

R.. GitHub STOP HELPING ICE