Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault while accessing a function-static structure via returned pointer

I have the following structure:

struct sys_config_s
{
  char server_addr[256];
  char listen_port[100];
  char server_port[100];
  char logfile[PATH_MAX];
  char pidfile[PATH_MAX];
  char libfile[PATH_MAX];
  int  debug_flag;
  unsigned long connect_delay;
};
typedef struct sys_config_s sys_config_t;

I also have a function defined in a static library (let's call it A.lib):

sys_config_t* sys_get_config(void)
{
  static sys_config_t config;
  return &config;
}

I then have a program (let's call it B) and a dynamic library (let's call it C). Both B and C link with A.lib. At runtime B opens C via dlopen() and then gets an address to C's function func() via a call to dlsym().

void func(void)
{
  sys_get_config()->connect_delay = 1000;
}

The above code is the body of C's func() function and it produces a segmentation fault when reached. The segfault only occurs while running outside of gdb.

Why does that happen?

EDIT: Making sys_config_t config a global variable doesn't help.

like image 346
MasterM Avatar asked Sep 12 '11 16:09

MasterM


People also ask

What causes segmentation fault with pointers?

A segmentation fault usually occurs when you try to access data via pointers for which no memory has been allocated. It is thus good practice to initialize pointers with the value NULL, and set it back to NULL after the memory has been released.

How do you fix a segmentation fault?

See if your compiler or library can be set to check bounds on [i] , at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers. Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems.

What causes SIGSEGV?

SIGSEGV is triggered by the operating system, which detects that a process is carrying out a memory violation, and may terminate it as a result. SIGABRT (signal abort) is a signal triggered by a process itself.


1 Answers

The solution is trivial. Somehow, by a header mismatch, the PATH_MAX constant was defined differently in B's and C's compilation units. I need to be more careful in the future. (facepalms)

like image 136
MasterM Avatar answered Oct 21 '22 15:10

MasterM