簡體   English   中英

在char指針數組中進行malloc分配時接收segfault

[英]Receiving segfault while mallocing within an array of char pointers

我正在編寫一個簡單的c程序,該程序將從文本文件中讀取行到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

getRestaurantsrestaurantsArray被聲明為char ***Array *restaurantsArray[index] = …; ,它將采用restaurantsArray[index]並嘗試將其用作指針(通過應用*運算符)。 但是restaurantsArray僅僅是mainrestaurantsArrayCopy的指針。 restaurantsArrayCopy僅僅是一個對象,而不是數組。 它只是一個char ** getRestaurants ,使用restaurantsArray[index]用什么,但零index使用一些不確定的事情。

無需將main &restaurantsArrayCopy傳遞給getRestaurants 只需傳遞restaurantsArray 這是指向已分配空間的指針。

然后,在getRestaurants ,而不是*restaurantsArray[index] = …; ,使用restaurantsArray[index] = …; ,不帶* 這將為restaurantsArray的元素分配一個值,這就是您想要做的。 同樣,刪除strcpyprintf中的*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM