动态字符串数组中的分段错误

时间:2020-10-29 01:37:56

标签: arrays c string dynamic

我有一个动态调整大小的字符串数组(在编译时我不知道字符串的大小),这一直给我一个分段错误错误。该数组包含在名为hm的结构中,它具有一个用于字符串的数组以及一个用于值的数组。代码的这一部分仅是在将新字符串添加到结构时正确调整字符串数组的大小。 我对C和struct还是比较陌生,因此,如果有更好的方法来实现这一点,我很想听听它。我已经尝试过寻找这种情况,大多数似乎是使用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;

1 个答案:

答案 0 :(得分:1)

问题在于,当您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() definition,当您拨打电话时:

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

其表现为:

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