Although this might be a duplicate post, I wanted to make sure how it works in my specific code.
What I wanna achieve?
Sending and receiving a struct over TCP/IP connection.
What I have so far?
Sender
initialize structs:
typedef struct soutputdata {
unsigned long long ull_date;
unsigned int ui_ixl;
unsigned int ui_type;
unsigned int ui_index;
char c_values[64][2];
int i_valueid;
} s_OUTPUTDATA;
typedef struct sheader {
int i_head;
} s_HEADER;
typedef struct soutdata {
s_HEADER *sHeader;
s_OUTPUTDATA *sDATAout;
} s_OUTDATA;
I now want to send an s_OUTDATA struct to a connected TCP client.
allocate memory (is this correct?):
s_OUTDATA *poutData = malloc(sizeof(s_OUTDATA));
poutData->sDATAout = malloc(sizeof(s_OUTPUTDATA));
poutData->sHeader = malloc(sizeof(s_HEADER));
Sending the struct (how can i get the correct size of the whole s_OUTDATA struct?):
if ((send(sendSocket, poutData, 1024, 0)) == -1) {
fprintf(errlog, "%.3f error: %s(): Failure Sending Message!\n", gettime(), __func__);
close(sendSocket);
}
Receiver
initialize structs:
typedef struct soutputdata {
unsigned long long ull_date;
unsigned int ui_ixl;
unsigned int ui_type;
unsigned int ui_index;
char c_values[64][2];
int i_valueid;
} s_OUTPUTDATA;
typedef struct sheader {
int i_head;
} s_HEADER;
typedef struct soutdata {
s_HEADER *sHeader;
s_OUTPUTDATA *sDATAout;
} s_OUTDATA;
allocate memory (is this correct?):
s_OUTDATA *p = malloc(sizeof(s_OUTDATA));
poutData->sDATAout = malloc(sizeof(s_OUTPUTDATA));
poutData->sHeader = malloc(sizeof(s_HEADER));
Receiving the struct:
if ((num = recv(newSocket, p, 1024,0)) == -1) {
perror("recv");
exit(1);
}
else if (num == 0) {
printf("Connection closed\n");
}
What is the problem?
When trying to work with the received data I get a segmentation fault.
printf("ui_index: %d\n", p->sDATAout->ui_index);
What am I missing?
I presume I have done sth wrong with the memory allocation but I am not sure what and how to solve it.