Print "Hello world" before main() function in C
The following program copied from Quora, that print "Hello world"
before main()
function.
#include <stdio.h>
#include <unistd.h>
int main(void)
{
return 0;
}
void _start(void)
{
printf ("hello, worldn");
int ret = main();
_exit (ret);
}
Then, I compiled above program on Ubuntu-14.04 GCC compiler using following command
gcc -nostartfiles hello.c
And ran a.out
executable file, But I got Segmentation fault (core dumped)
? So, Why Segmentation fault ?
_start
is the real entrypoint of the executable, that is normally taken by the C runtime to initialize its stuff - including stdio -, call functions marked with the constructor
attribute and then call your main
entrypoint. If you take it and try to use stuff from the standard library (such as printf
) you are living dangerously, because you are using stuff that hasn't been initialized yet.
What you can do, however, is to bypass the C runtime completely, and print using a straight syscall, such as write
.
上一篇: 返回智能指针时的最佳做法