Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile and run program without main() in C

I'm trying to compile and run following program without main() function in C. I have compiled my program using the following command.

gcc -nostartfiles nomain.c 

And compiler gives warning

/usr/bin/ld: warning: cannot find entry symbol _start; defaulting to 0000000000400340 

Ok, No problem. then, I have run executable file(a.out), both printf statements print successfully, and then get segmentation fault.

So, my question is, Why segmentation fault after successfully execute print statements?

my code:

#include <stdio.h>  void nomain() {         printf("Hello World...\n");         printf("Successfully run without main...\n"); } 

output:

Hello World... Successfully run without main... Segmentation fault (core dumped) 

Note:

Here, -nostartfiles gcc flag prevents the compiler from using standard startup files when linking

like image 623
msc Avatar asked Feb 19 '17 14:02

msc


People also ask

Can we compile without main () in C?

The answer is yes. We can write program, that has no main() function. In many places, we have seen that the main() is the entry point of a program execution. Just from the programmers perspective this is true.

Can we compile and execute a program without main () function?

yes it is possible to write a program without main().

What happens without main () function in C program?

How to write a running C code without main()? It's an entry point of every C/C++ program. All Predefined and User-defined Functions are called directly or indirectly through the main.


1 Answers

Let's have a look at the generated assembly of your program:

.LC0:         .string "Hello World..." .LC1:         .string "Successfully run without main..." nomain:         push    rbp         mov     rbp, rsp         mov     edi, OFFSET FLAT:.LC0         call    puts         mov     edi, OFFSET FLAT:.LC1         call    puts         nop         pop     rbp         ret 

Note the ret statement. Your program's entry point is determined to be nomain, all is fine with that. But once the function returns, it attempts to jump into an address on the call stack... that isn't populated. That's an illegal access and a segmentation fault follows.

A quick solution would be to call exit() at the end of your program (and assuming C11 we might as well mark the function as _Noreturn):

#include <stdio.h> #include <stdlib.h>  _Noreturn void nomain(void) {     printf("Hello World...\n");     printf("Successfully run without main...\n");     exit(0); } 

In fact, now your function behaves pretty much like a regular main function, since after returning from main, the exit function is called with main's return value.

like image 156
StoryTeller - Unslander Monica Avatar answered Nov 16 '22 00:11

StoryTeller - Unslander Monica