gcc - Compile and run program without main() in C -
i'm trying compile , run following program without main() function in c. have compiled program using following command.
gcc -nostartfiles nomain.c and compiler gives warning
/usr/bin/ld: warning: cannot find entry symbol _start; defaulting 0000000000400340 ok, no problem. then, have run executable file(a.out), both printf statements print successfully, , segmentation fault.
so, question is, why segmentation fault after execute print statements?
my code:
#include <stdio.h> void nomain() { printf("hello world...\n"); printf("successfully run without main...\n"); } output:
hello world... run without main... segmentation fault (core dumped)
let's have @ generated assembly of 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 ret statement. programs entry point determined nomain, fine that. once function returns, attempts jump address on call stack... isn't populated. that's illegal access , segmentation fault follows.
a quick solution call exit @ end of program (and assuming c11 might mark function _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, function behaves pretty regular main function, since after returning main, exit function called main's return value.
Comments
Post a Comment