2

I understand functions like data items have addresses and the address of a function is the memory address where the stored machine language code for the function begins. I have this code;

#include <iostream>

using namespace std;

int x(int);
char * y(char *);

int main() {

    x(5);
    y("hello");

    int (*p) (int); //pointer to function x
    char * (*q) (char *); //pointer to function y

    p = &x; //holds the address of function x
    q = &y; //holds the address of function y

    cout << p << endl;
    cout << q;

    return 0;
}

int x(int a) {
    return (a * a);
}

char * y(char *b) {
    return (b);
} 

So is there a way i can force the cpu to execute a particular function before another using the function addresses?

Upon compiling, the program prints out both addresses as 1. I was expecting hexadecimal values like that of data items. even when I print the dereferenced values, I still get 1, what is going on?

Also, if both function addresses are 1, how does the cpu know which function to execute first?

EDIT:

one of my questions is left unanswered, which i find very important! Doesn't wholly make it a duplicate even though some are.

  • 2
    `operator<<` probably does something weird with streams and function pointers. E.g. `endl` is a function pointer, and `cout << endl` just does `endl(cout)`. – melpomene Oct 25 '16 at 22:08
  • Well, if you go the "old way" and use printf you will get the proper address: printf("%p %p\n", p, q); //prints two hex values – Caladan Oct 25 '16 at 22:13

2 Answers2

1

The std::cout will convert function pointers to a bool, and since the function pointer is non-zero, the value 1 is displayed.

To display as hex value, cast the function pointer to a void *, for example:

cout << (void*)p << endl;
Kendrick Wong
  • 394
  • 1
  • 12
-1

You can retrieve these functions addresses by typing : cout<< &p << endl << &q << endl; The & operator gives you back the address of block memory in which the variable after the & operator is set.

pippo
  • 774
  • 6
  • 10
  • 2
    wouldn't that rather be the addresses of the pointers holding the addresses of the pointer to the functions and not the pointers to the functions themselves? – Richardson Ansong Oct 25 '16 at 22:17
  • @Nana Yes, sorry I didn't understand correctly your question: &p and &q are the addr of pointers who are pointing to the addr of your functions. So the Wong answer is correct. For your last answer, yes, there are some methods to modify the right flow of your program. For example one is to use a buffer overflow to overwrite some cpu register to execute arbitrary piece of code (in particular the EIP register, the one handling the pointer to the next machine instruction for being executed). Otherwise it depends on your order in which you put your functions. – pippo Oct 28 '16 at 22:48