The following code 1 is fine
#include <stdio.h> // code 1
main()
{
printf("%u",main);
}
but this code 2 gives segmentation fault.
#include <stdio.h> // code 2
main()
{
printf("%u",main());
}
I’m not getting what’s the difference between main and main()?
Did you compile with all warnings enabled from your compiler? With
gccthat means giving the-Wallargument togcc(and-gis useful for debugging info).First, your
printf("%u", main)should beprintf("%p\n", main). The%pprints a pointer (technically function pointers are not data pointers as needed for%p, practically they often have the same size and similar representation), and you should end your format strings with newline\n. This takes the address of themainfunction and passes that address toprintf.Then, your second
printf("%u", main())is callingprintfwith an argument obtained by a recursive call to themainfunction. This recursion never ends, and you blow up your call stack (i.e. have a stack overflow), so get aSIGSEGVon Unix.Pedantically,
mainis a very special name for C standard, and you probably should not call it (it is called auto-magically by startup code incrt0.o). Recursing onmainis very bad taste and may be illegal.See also my other answer here.