segmentation fault by Special functions

For an observation purpose, I wrote a program using _start(), _init(), _fini(), goal is to not to use startfiles. the code is as follows

#include <stdio.h>
void test()
{
printf("n%s: n",__func__);
printf("library test routine invokedn");
int a=3,b=2;
int sum=a+b;
printf("sum=%dn",sum);
getchar();
_fini();
}

int _start()
{
printf("n%s: n",__func__);
printf("in library start routinen");
test();
return 0;
}
int _init()
{
printf("n%s: n",__func__);
printf("in library init routinen");
return 0;
}

int _fini()
{
printf("n%s: n",__func__);
printf("in library fini routinen");
return 0;
}

complied with

gcc -nostartfiles test.c -o test

and the output is

_start: 
in library start routine

test: 
library test routine invoked
sum=5
l

_fini: 
in library fini routine
Segmentation fault (core dumped)

Here I want to know why the executable gave segmentation fault?? Do I need to specify as it is end of the program?? If so, how?? What can be done to overcome the segmentation fault?? Another question is that these _start(),_init(),_fini() are only used when dealing with libraries??? Please


The _start routine cannot return. Normally, it calls __libc_start_main which calls main . Then when main returns, __libc_start_main calls exit with the return value of main .

Since you're defining _start yourself and not calling __libc_start_main , you need to explicitly call exit . You're getting a sigfault because that function is not expected to return.

See this question for more detail.

链接地址: http://www.djcxy.com/p/79932.html

上一篇: 为什么写作主要; 在C给出段错误

下一篇: 通过特殊功能分段故障