Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the address of a function?

I let gcc compile the following example using -Wall -pedantic:

#include <stdio.h>

int main(void)
{
  printf("main: %p\n", main); /* line 5 */
  printf("main: %p\n", (void*) main); /* line 6 */

  return 0;
}

I get:

main.c:5: warning: format ‘%p’ expects type ‘void *’, but argument 2 has type ‘int (*)()’
main.c:6: warning: ISO C forbids conversion of function pointer to object pointer type

Line 5 made my change the code like in line 6.

What am I missing to remove the warning when printing a function's address?

like image 895
alk Avatar asked Jun 07 '12 13:06

alk


People also ask

How do you find a function address?

We can get the address of a function by just writing the function's name without parentheses. Please refer function pointer in C for details. In C/C++, name of a function can be used to find address of function.

How do I print an address from printf?

You can print a pointer value using printf with the %p format specifier. To do so, you should convert the pointer to type void * first using a cast (see below for void * pointers), although on machines that don't have different representations for different pointer types, this may not be necessary.

What is the address of the main function?

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.

Do functions have address C?

Address of a function in C or C++ In C or C++, the variables are stored into memory, so we can get their memory addresses. Similarly, the functions also are stored into the memory, so they also have some addresses. To get the address we can use the function name only without using the parenthesis.


2 Answers

This is essentially the only portable way to print a function pointer.

size_t i;
int (*ptr_to_main)() = main;
for (i=0; i<sizeof ptr_to_main; i++)
    printf("%.2x", ((unsigned char *)&ptr_to_main)[i]);
putchar('\n');
like image 136
R.. GitHub STOP HELPING ICE Avatar answered Sep 28 '22 00:09

R.. GitHub STOP HELPING ICE


This whole idea is indeed non-portable, since some systems use different sized pointers to code and data.

What you really need is platform-specific knowledge of how big a function pointer is, and a cast to an integral type of that size. Unfortunately, I don't think anyone has standardized a intfuncptr_t analagous to intptr_t which can hold any data pointer.


As R. notes in his answer, you can always treat the pointer as an array of (possibly signed or unsigned) char, this way you don't need any integral type of the correct size.

like image 22
Ben Voigt Avatar answered Sep 28 '22 01:09

Ben Voigt