在动态结构数组中使用realloc [英] Using realloc in dynamic structure array

查看:109
本文介绍了在动态结构数组中使用realloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用realloc动态创建结构实例,并在进行时用临时结构中的数据填充它.当程序再次到达要再次分配该结构的指针的行时,程序崩溃,但是我不确定如何构造该函数.我有以下代码:

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;

}

推荐答案

我看到一个潜在的问题:

I see one potential problem:

您将g设置为0,即

int g =0;

在调用create_valid()之前不会增加它.您正在使用此值在该函数内部分配内存:

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));

所以现在g0.

稍后在下一行中取消引用此指针

Later in the next line you dereference this pointer

valid[g] =  *temp;

这是您尚未分配的一些内存,因为realloc()没有为您分配内存,因为您向其传递了0.因此崩溃.

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.

这篇关于在动态结构数组中使用realloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆