views:

71

answers:

3

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 welcome. Also, my first question, so please be gentle, am really trying to learn. Thanks!

+3  A: 

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.

sharptooth
@sharptooth: Right, so the output here represents the location where this particular function has been loaded as part of the code-segment? Is there a way for a C program to print the data segment, code segment begin/end addresses?
helpmelearn
@helpmelearn: Yes, that's the address where the function start is located. I'm not aware of a solution for finding the segments addresses and I suppose it would be implementation-dependent. Perhaps there's some utility program that can do this for just any process.
sharptooth
+2  A: 

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.

alt text

MovieYoda
A: 

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.

kasterma