【问题标题】:Receiving segfault while mallocing within an array of char pointers在 char 指针数组中进行 malloc 时接收段错误
【发布时间】:2019-11-28 22:34:22
【问题描述】:

我正在编写一个简单的 c 程序,它将文本文件中的行读入 char **。在我的主函数中,我创建了 char * 数组,为其分配内存,并将指向该数组的指针传递给另一个函数,以使用 char * 填充数组中的每个索引,该 char * 表示文本文件中每一行的内容。

由于某种与我的内存管理相关的原因,我猜测,我在 while 循环的第三次迭代中收到分段错误,它将字符串复制到字符串数组中。这是为什么呢?

我的代码:

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

void getRestaurants(char ***restaurantsArray) {
    FILE *restaurantsFile = fopen("./restaurants.txt", "r");
    char *restaurant = (char *)malloc(50 * sizeof(char));
    char *restaurantCopy = restaurant;

    //fopen will return null if it is unable to read the file
    if (restaurantsFile == NULL) {
    free(restaurant);
    return;
    }

    int index = 0;
    while (fgets(restaurantCopy, 50, restaurantsFile)) {
        // segfault occurs the third time the following line is executed
        *restaurantsArray[index] = (char*)malloc(50 * sizeof(char));
        strcpy(*restaurantsArray[index], restaurantCopy);
        printf("%s", restaurantCopy);
        printf("%s", *restaurantsArray[index]);
        index++;
    }

    fclose(restaurantsFile);
    free(restaurant);
}

void main() {
    char **restaurantsArray = (char **)malloc(100 * sizeof(char *));
    char **restaurantsArrayCopy = restaurantsArray;
    getRestaurants(&restaurantsArrayCopy);
}

预期结果:

firstline
firstline
secondline
secondline
thirdline
thirdline

以此类推,如果提供的 restaurant.txt 文件包含:

firstline
secondline
thirdline

【问题讨论】:

  • 为什么要使用三重指针?如果不修改值,为什么要通过引用传递参数?为什么要在函数外分配而在函数内释放?

标签: c arrays pointers segmentation-fault


【解决方案1】:

getRestaurants 中,restaurantsArray 被声明为char ***Array。在*restaurantsArray[index] = …; 行中,它采用restaurantsArray[index] 并尝试将其用作指针(通过应用* 运算符)。但是restaurantsArray 只是指向main 中的restaurantsArrayCopy 的指针。 restaurantsArrayCopy 只是一个对象,而不是一个数组。它只是一个char **。在getRestaurants 中,将restaurantsArray[index]index 使用除零以外的任何值都会使用一些未定义的东西。

无需将&amp;restaurantsArrayCopymain 传递到getRestaurants。只需通过restaurantsArray。这是一个指向分配空间的指针。

然后,在getRestaurants 中,使用restaurantsArray[index] = …; 代替*restaurantsArray[index] = …;,而不使用*。这将为restaurantsArray 中的元素分配一个值,这是您想要做的。同样,删除strcpyprintf 中的*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 2020-05-12
    相关资源
    最近更新 更多