Is it possible to address the address of the main () function?

According to this answer , using the main () function is illegal (ยง3.6.1.3), and the function is used if its name is displayed in a potentially evaluated expression (ยง 3.2).

Suppose I have this code:

printf( "%p", &main ); 

in which the name of the main() function appears in the &main expression.

Will the above code be illegal?

+7
source share
3 answers

Yes. As you quote, the standard says that you cannot use main .

Note that the address of the function does not match "%p" . The corresponding argument must be of type void* ; any other type (except maybe char* ) is illegal, and leads to undefined behavior.

+3
source

Since main not used (you do not rate it), then it must be legal in accordance with the link you provided.

0
source

It is not recommended to use a pointer to main() or the address of main() , but ..

In any case, this is allowed, since each function (and any character, for example, a variable) has its own address. And the main () address may be required, especially when you write code for embedded systems and play with dynamic code loading or runtime checking. Or there is a bootloader and actual firmware.

Often, main() is the entry point to dynamically loaded code (for example, from FLASH to RAM) and, thus, it is referenced (called directly or assigned to the corresponding pointer) in the loader.

Refer to MicroC-OS / II or VxWorks - use main() this way

-3
source

All Articles