我对结构数组的malloc和realloc有什么错?

问题描述

我试图在C中构建结构数组,但不定义数组最大大小的长度。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct text {
   char *final;
} text;

int main() {
    int n,sizearray = 10,i;
    char *str;
    text *testo;
    testo = (text *)malloc(sizeof(text) * sizearray);

    fgets(str,1024,stdin);
    i = 0;
    while (str[0] != 'q') {
        if (i == sizearray - 1) {
            testo = (text *)realloc(testo,sizearray * 2 * sizeof(text));
        }
        n = strlen(str);
        n = n + 1;
        testo[i].finale = (char *)malloc(sizeof(char) * n);
        strcpy(testo[i].finale,str);
        i++;
        fgets(str,stdin);
    }

    for (i = 0; i < sizearray; i++)
        printf("%s \n",testo[i].finale);

    return 0;
}

这给了我

process finished with exit code 139 (interrupted by signal 11:SIGSEV).

我在做什么错了?

解决方法

str未初始化。使用malloc分配内存,或者使用char str[1024]将其定义为数组。

,

您的代码中存在多个问题:

  • [主要] str是未初始化的指针。您应将其设置为由char定义的char str[1024]的数组。
  • [主要] ,当您将数组的大小加倍时,您不会调整sizearray,因此,在初次尝试i = 9后,您将永远不会重新分配数组。 / li>
  • [主要] ,最后一个循环进入sizearray,但数组末尾可能有许多未初始化的条目。您应该停止存储在数组中的最后一个条目。
  • 您还应该检查fgets()的返回值,以免在文件过早结束时发生无限循环。
  • 您应该测试潜在的内存分配失败,以避免未定义的行为。

这是修改后的版本:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct text {
   char *finale;
} text;

int main() {
    char str[1024];
    text *testo = NULL;
    size_t sizearray = 0;
    size_t i,n = 0;

    while (fgets(str,sizeof str,stdin) && *str != 'q') {
        if (n == sizearray) {
            /* increase the size of the array by the golden ratio */
            sizearray += sizearray / 2 + sizearray / 8 + 10;
            testo = realloc(testo,sizearray * sizeof(text));
            if (testo == NULL) {
                fprintf(stderr,"out of memory\n");
                return 1;
            }
        }
        testo[n].finale = strdup(str);
        if (testo[n].finale == NULL) {
            fprintf(stderr,"out of memory\n");
            return 1;
        }
        n++;
    }

    for (i = 0; i < n; i++) {
        printf("%s",testo[i].finale);
    }
    for (i = 0; i < n; i++) {
        free(testo[i].finale);
    }
    free(testo);
    return 0;
}