I am trying to use realloc to dynamically create instances of a struct, filling it with data from a temporary structure as I go. The program crashes when it reaches the line to malloc a pointer of the structure a second time but I am not sure how I should structure this function. I have the following code:
#define MAX_STRING 50
struct data {
int ref;
int port;
char data[MAX_STRING+1];
}valid, invalid;
void read_file(FILE *file);
void validate(struct data* temp);
int g = 0;
int main(){
char inputfile[100];
FILE *file = fopen("file.txt" , "r");
if (file != NULL){
read_file (file);
}
else{
// Some code here..
}
return 0;
}
void read_file(FILE *file){
struct data* temp = malloc(sizeof(struct data));
char buf[1024];
while(!feof(file)){
fgets(buf, sizeof buf, file))
sscanf(buffer, "%d.%d.%s", &temp->ref, &temp->port, &temp->data);
validate(temp);
g++;
}
}
void validate(struct data* temp){
if((some condition) && (some condition))
{
create_valid(temp);
}
if((some condition) && (some condition))
{
create_invalid(temp);
}
}
I am unsure of how to structure the following function:
int create_vaild(struct data* temp){
struct data* valid = malloc(sizeof(struct data)); <<<<<<<<< Line that crashes
valid = realloc(valid, g * sizeof(struct data));
valid[g] = *temp;
if (valid[g] == NULL){
//error.
};
printf("\n%i:%i:%s\n", (valid+g)->ref, (valid+g)->port, (valid+g)->data);
return 0;
}