I have the following struct:
struct message {
int id;
int ack;
int data_len;
char *data;
time_t timer;
} *messages, *temp;
I am allocating a chunk of memory to hold upto numMessages amount of these structs:
messages = malloc(sizeof(messages)*numMessages);
And then n messages can be added by calling the function ReadFromFile(int), with count initialized to 0
void readFromFile(int n) {
char input_buff[4096];
int size = sizeof(struct message);
for (int i = 0; i < n; i++) {
bzero(input_buff, sizeof(input_buff));
int nread = fread(input_buff, 1 , msgSize, fp);
if (nread > 0) {
printf("adding message: %d\n", count);
temp = (struct message *) malloc (sizeof (struct message));
temp->data_len = nread;
temp->id = count; // set integer id
temp->data = malloc( sizeof(char) * ( nread ));
temp->ack = 0;
memcpy(temp->data, input_buff, nread);
memcpy(&messages[count],temp,sizeof(temp));
count++;
free(temp);
}
if (nread < sizeof(input_buff)) {
if (feof(fp))
printf("End of file\n");
free(filename);
close(fp);
break;
}
if (ferror(fp)) {
printf("Error reading\n");
break;
}
}
}
HOWEVER, messages[count].data isn't being stored. However, if I swap the lines:
temp->data_len = nread;
and
temp->data = malloc( sizeof(char) * ( nread ));
The data is properly stored, but now data_len isn't stored? What am I doing wrong? Besides the fact I'm sure that having a pointer temp and than coping the memory is redundant...
Thank you!