nevermindmyname
nevermindmyname

Reputation: 21

Segfault only when using pkg-config --libs for glib.h

I have the following piece of code, compiled with gcc `pkg-config --cflags glib-2.0` test.c -o test the code works, but only when I use gcc `pkg-config --cflags --libs glib-2.0` test.c -o test the code gets segfault when running.

#include <glib.h>     

typedef struct _mystruct{
    int a;
}my;                                                                         
                                                                                               
static void set_int(my *mert){                                                                 
  mert->a = 5;                                                                                   
}                                                                                                                                                                                                                                                                                        
                                                                                           
int main() {                                                                                                                                                        
  my *myInt;                                                                                                                                                                             
  set_int(myInt);                                                                                                                                                                    
}                                 

I tried with GDB, when the program is compiled with --libs the segfault comes from here

0x0000000000401132 in set_int (mert=0x0) at test.c:5
5       mert->a = 5;

But when it is compiled only with --cflags all is on its place

Breakpoint 1, set_int (mert=0x7ffff7ffdab0 <_rtld_local+2736>) at test.c:5
5       mert->a = 5;

I have also tried with gcc `pkg-config --cflags glib-2.0` test.c -o test `pkg-config --libs glib-2.0` but it doesn't change anything.

Upvotes: 2

Views: 80

Answers (1)

user9706
user9706

Reputation:

myInt is an uninitialized pointer and it happens to be NULL in the case where your program is segfault'ing. You pointer needs to reference a struct as set_int() dereferences said pointer:

int main() {             
  my myInt;                            
  set_int(&myInt);
}

Or you could could zero initialize your struct and take it's address if you want myInt to be a pointer:

int main() {
  my *myInt = &(my) { 0 };
  set_int(myInt);
}

Upvotes: 3

Related Questions