c - 在动态结构数组中使用 realloc

标签 c struct malloc structure realloc

我正在尝试使用 realloc 来动态创建结构的实例,并在创建过程中用临时结构中的数据填充它。程序在第二次到达 malloc 结构指针的行时崩溃,但我不确定我应该如何构造这个函数。我有以下代码:

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

我不确定如何构造以下函数:

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;

}

最佳答案

我看到一个潜在的问题:

你将 g 设置为 0 即

int g =0;

您没有在调用 create_valid() 之前递增它。您正在使用此值在该函数内分配内存:

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

所以现在 g0

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

valid[g] =  *temp;

这是一些你没有分配的内存,因为 realloc() 没有为你分配内存,因为你将 0 传递给它。因此崩溃。

关于c - 在动态结构数组中使用 realloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490232/

相关文章:

c - TLB 对 Cortex-A9 影响的测量

arrays - 使用结构体存储动态数据

Calloc 会导致段错误,但不会导致 malloc

C结构初始化和指针

c - Malloc 结构体数组

在 C 中使用 for 循环创建链表并赋值

c - 如何在C中将字符串转换为整数?

c - 如何在 C 中定位输入文本光标?

c - scanf 不扫描 %c 字符而是跳过该语句,这是为什么?

c++ - 为什么要在 struct 和 union 上使用 typedef?