簡體   English   中英

動態字符串數組中的分段錯誤

[英]Segmentation fault in dynamic string array

我有一個動態大小的字符串數組(我不知道編譯時字符串的大小),它不斷給我一個分段錯誤錯誤。 該數組包含在一個名為hm的結構中,它有一個字符串數組和一個值數組。 這部分代碼只是在將新字符串添加到結構中時正確調整字符串數組的大小。 我對 C 和結構比較陌生,所以如果有更好的方法來實現它,我很樂意聽到它。 我已經嘗試四處尋找這種情況,並且大多數似乎是使用sizeof(char)而不是sizeof(char*)的外部數組存在問題,但是當我更改時,問題仍然發生。

//problematic part of the function
char** t = (char**)realloc(hm->keys, hm->size * sizeof(char*));
if (t) hm->keys = t;
for (i = 0; i < hm->size; i++) {
    char* temp = (char*)realloc(hm->keys[i], hm->largestKey * sizeof(char)); //seg fault here
    if (temp) {
        hm->keys[i] = temp;
    }
}

//struct
typedef struct HM_struct {
    size_t size;
    size_t largestKey;
    char** keys;
    int* values;

    void (*add)(struct HM_struct* hm, char* key, int value);
} HM;

問題是,當您realloc()並增加分配的內存大小時,新內存未初始化(或使用調試庫初始化為一個標記值)。 所以,假設你知道oldSize ,一個快速的解決方法是:

char** t = realloc(hm->keys, hm->size * sizeof(char*)); // As before
if (t) hm->keys = t; // As before
for (i = oldSize; i < hm->size; i++)
    hm->keys[i] = NULL;

現在,根據realloc()定義,當您調用時:

char* temp = realloc(NULL, hm->largestKey * sizeof(char));

它的行為如下:

char* temp = malloc(hm->largestKey * sizeof(char));

暫無
暫無

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

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