Using realloc in dynamic structure array

2019-08-13 02:53发布

问题:

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;

}

回答1:

I see one potential problem:

You have g set to 0 i.e.

int g =0;

You are not incrementing it before the call to create_valid(). You are using this value to allocate memory inside that functions:

valid = realloc(valid, g * sizeof(struct data));

So now g is 0.

Later in the next line you dereference this pointer

valid[g] =  *temp;

This is some memory which you have not allocated as realloc() didn't allocate memory for you becasue you passed 0 to it.Hence the crash.