How to fix Segmentation fault while accessing shared library function in C programming?

i created a shared library file named Library.c

#include<stdio.h>
int Addition(int a, int b)
{
    int s;
    s = a + b;
    return s;
}

debug the share library

gcc -shared -o libshared.so Library.c

create a small program that access the shared library function

#include<stdio.h>
int Addition(int a, int b);
void main(int argc, char *argv[])
{
    int total;
    total = Addition(19, 23);
    printf("Total = %d\n", total);
}

debug the program

gcc -o foo foo.c -L. -shared

execute the program and i get the error

Segmentation fault

using gdb i got the current output

Program received signal SIGSEGV, Segmentation fault.
0x0000000000000001 in ?? ()
(gdb) bt
#0  0x0000000000000001 in ?? ()
#1  0x00007fffffffe4ca in ?? ()
#2  0x0000000000000000 in ?? ()
csegmentation-faultshared-libraries

Answers

answered 3 days ago Tomek Szpakowicz #1

In the 2nd gcc command:

gcc -o foo foo.c -L. -shared

you have -shared instead of -lshared. So instead of linking to libshared.so you build foo as a shared library. For some reason on your system trying to execute a shared library causes a segfault instead of producing a more meaningful error message.

comments powered by Disqus