Ivanov Dmitry Ivanov Dmitry -4 years ago 195
C Question

Array of Struct pointers, get segfault in c

#define MAX_SPACES 10
#define MAX_SIMPLE_EVENTS 5000
#define MAX_USER_EVENTS 1000

struct {
EventSpace* p_spaces[MAX_SPACES];
SimpleEvent* p_simple_events[MAX_SIMPLE_EVENTS];
UserEvent* p_user_events[MAX_USER_EVENTS];
}* G_manager;

static void add_space(EventSpace* space){
static uint16_t index = 0;
(*G_manager).p_spaces[index] = space;

After running in gdb got:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400559 in add_space (space=0x7fffffffdf30)

How to impove it?

Answer Source

At least in the code you're showing, you haven't actually allocated the memory for the structure containing the arrays; you've only created a pointer. So when you dereference that pointer meaning to write into an instance of the structure, you hit a random memory address and got the relatively tame result of your program crashing.

You could change G_manager from a pointer-to-struct to an instance of the struct itself; or you can malloc a buffer big enough for the structure and assign that buffer to G_manager

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download