I am building a building server and a client programs. I am trying to make them communicate via a socket (in case it is important I am writing on a 32-bit OS Linux and both the client and the server will be running on the same systems). Now, I have the next structs:
struct config_line {
char name[MAX_WORD]; //1 byte
int time; //4 bytes
};
struct config {
struct config_line *lines; // 4 bytes, points to a struct of 8 bytes
int count; // 4 bytes
};
configData is defined as followes
struct config configData; // global
I send that configData like this:
send (clients [scn], &configData, sizeof (configData), 0)
Now, inside my client program, when I try to access
configData.lines[configIndex].name
it segfaults on that line. Anyone has an idea why?
When you send the type
config, it has space for a pointer ofconfig_line, but does not contain the data in the (I assume) array dynamically allocated where that pointer points to.Then the client gets the
configtype, but it has invalid pointer value (on the client) as the array is not sent and the pointer is not set to that array. (The pointer is valid on the sender, but not on the client — they use separate memory space)You will either need to specify a fixed size array in
configthat can contain a max number of elements you will ever want to store (then the sending will contain that data), or send the contents of the dynamic array and parse it on the client side and set theconfigpointer to that array, so the dereferencing is valid