2

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 invoked\n");
int a=3,b=2;
int sum=a+b;
printf("sum=%d\n",sum);
getchar();
_fini();
}

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

int _fini()
{
printf("\n%s: \n",__func__);
printf("in library fini routine\n");
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

GShaik
  • 197
  • 1
  • 17

1 Answers1

1

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.

Community
  • 1
  • 1
dbush
  • 205,898
  • 23
  • 218
  • 273