Using realloc in dynamic structure array

半世苍凉 提交于 2019-12-11 13:41:37

问题


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.



来源:https://stackoverflow.com/questions/27490232/using-realloc-in-dynamic-structure-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!