开发者

What does the pointer value of a function pointer represent?

Trying to understand what the pointer to function actually represent? Is it the address in the code segment where the function resides?

For ex: this piece of code:

#include <stdio.h>

void foo(void)
{
}

int main(void)
{
    int a = 10;
    printf("a's address: %p\n", &a);
    printf("foo's address: %p\n", foo);
    return 0;
}

... prints this:

[sh/prog-exercises/adam]:./a.out 
a's address: 0xbfffb414 
foo's address: 0x8048430

I guess I am a little confused with how exactly stack/heap of a process relates with the ELF data-segment/code-segment. Any helpful pointers would be really开发者_JAVA百科 welcome. Also, my first question, so please be gentle, am really trying to learn. Thanks!


That's the address of the function entry point - start of its code. The a variable is located on stack, so no surprise its address differs significantly - stack and code are assigned different code regions taht can be quite far apart.


This image from the book UNIX: Systems Programming should make things clear.

At the bottom of the diagram, you have your program text (low addresses). As can be verified from your program. That's where foo() would reside.

What does the pointer value of a function pointer represent?


One thing to keep in mind is that your code is not entirely standards compliant. If you use gcc -Wall -Wextra -pedantic -ansi you will get a complaint about the line where you are printing the function pointer. This is because the standard does not guarantee that function pointers can be converted to void pointers. C is designed to work on many different architectures, and if the architecture is a Harvard architecture (separate instruction and data memory) there might be good reasons to make these pointers different sizes.

I guess that in practice it is not likely to matter, but a good factoid to be aware of. Esp when you are trying to learn the intimate details of C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜