旧大小的 realloc() 问题

realloc() problems with the old size

我想从一个文件中读取很多信息,所以我需要一个动态内存。 这就是为什么我在 main 中为我的结构使用 malloc。 我想重新分配我从文件中获得的每一行,但他说 "realloc(): invalid old size",甚至没有重新分配一次。

typedef struct{
 int anzahl;
 int ANR;
 char MHD[10];
 char Bezeichnung[20];
 char VPE[5];
 float Preis;
 float gesamtpreis;
}Ware; 

int DateiLesen(Ware *Rechnung)
{
FILE *datei_lesen = NULL;
char trennung[] = " :,;\n[=10=]=";
char zeilen_lesen[256] = {0};
char *formatierer = NULL;
int count = 0;

datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
    count++;
}
fclose(datei_lesen);
if(count == 0)
{
    return -1;
}
datei_lesen = fopen("artikel.txt","r");
while(fgets(zeilen_lesen,256,datei_lesen))
{
    fputs(zeilen_lesen,datei_lesen);
    formatierer = strtok(zeilen_lesen,trennung);
    if(atoi(formatierer) >= 100000)
    {
        Rechnung->ANR = atoi(formatierer);
        formatierer = strtok(NULL,trennung);
        strcpy(Rechnung->MHD,formatierer);
        formatierer = strtok(NULL,trennung);
        strcpy(Rechnung->Bezeichnung,formatierer);
        formatierer = strtok(NULL,trennung);
        strcpy(Rechnung->VPE,formatierer);
        formatierer = strtok(NULL,trennung);
        Rechnung->Preis = atoi(formatierer);
        Rechnung =  realloc(Rechnung,1*sizeof(Ware));
        //Rechnung = (Ware*) realloc(Rechnung,1);
        Rechnung++;
    }
}
fclose(datei_lesen);
return 0;
}


int main(void) {
Ware *Rechnung = (Ware*) malloc(sizeof(Ware));
int test = 0;

initialisiere(&Rechnung);
test = DateiLesen(&Rechnung);
return EXIT_SUCCESS;
}

这不是增长数组的方式。

首先,

Rechnung++;

很好,但 Rechnung 不再是之前调用 mallocrealloc 的指针 return。所以你既不能 realloc 也不能 free 它。

第二,

Rechnung =  realloc(Rechnung,1*sizeof(Ware));

如果您想无论如何都将数组的大小始终保留为 1 个元素,那很好。如果你想增加尺寸,你需要输入新的尺寸。

典型的数组增长循环通常如下所示:

Data *array = NULL; // note it's fine to realloc a NULL
size_t size = 0;
while (fgets(...)) {
    size_t new_size = size + 1;
    Data *new_array = realloc(array, sizeof(Data) * new_size);
    if (new_array == NULL) {
       // report an error, exit, abort, try again, whatever
       // note having a separate `new_array` variable allows you 
       // to retain old data in `array` in the case of `realloc` erroring on you
    } else {
       array = new_array;
       array[size].foo = make_foo();
       array[size].bar = make_bar();
       size = new_size;
    }
}

注意你 从不 增加 array 因为你不能将增加的 array 传递给 realloc 。你不能也有这样的东西:

    Data *array = malloc(sizeof(Data));
    Data *current = data;
    while (...) {
        ...
        current->foo = make_foo();
        current->bar = make_bar();
        array = realloc(array, sizeof(Data) * new_size);
        current++;
    }

因为 realloc 可能并且将会 return 一个与传递的指针不同的指针,并且 current 将变得无效。所以使用普通的旧无聊数组索引。