【问题标题】:What am I doing wrong with malloc and realloc of array of struct?我对结构数组的 malloc 和 realloc 做错了什么?
【发布时间】:2020-08-17 14:18:40
【问题描述】:

我试图在 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, 1024, 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 分配内存,试试,char str [1024];
  • str 指向哪里?还要学习使用调试器。调试器会告诉您崩溃发生的哪里,这会为您提供有价值的提示,例如崩溃最有可能发生在fgets 此处,因此问题与fgets 之后的任何内容无关。

标签: arrays c malloc realloc


【解决方案1】:

您的代码中有多个问题:

  • [major] str 是一个未初始化的指针。您应该将其设为char 的数组,并使用char str[1024] 定义。
  • [major]当您将数组大小加倍时,您不会调整 sizearray,因此您将永远不会在初次尝试 i = 9 后重新分配数组。
  • [major]最终循环转到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;
}

【讨论】:

  • 哦,非常感谢,如果我只想释放我没有使用的空间怎么办?
  • 你可以在while循环之后添加text *tp = realloc(testo, n * sizeof(text)); if (tp != NULL) testo = tp;
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 2012-09-19
    • 2021-01-15
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多