简体   繁体   English

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

[英]Segmentation fault in dynamic string array

I have an array of strings that is dynamically sized (I won't know the size of the strings at compile) that keeps giving me a segmentation fault error.我有一个动态大小的字符串数组(我不知道编译时字符串的大小),它不断给我一个分段错误错误。 The array is contained in a struct called hm and it has an array for the strings as well as an array for values.该数组包含在一个名为hm的结构中,它有一个字符串数组和一个值数组。 This part of the code is only to resize the string array properly when a new string is added to the struct.这部分代码只是在将新字符串添加到结构中时正确调整字符串数组的大小。 I am relatively new to C and structs, so if there is a better way to implement this I would love to hear about it.我对 C 和结构比较陌生,所以如果有更好的方法来实现它,我很乐意听到它。 I have already tried looking around for this situation and most seem to be having the issue with the outer array using sizeof(char) instead of sizeof(char*) , but when I changed that the issue still happens.我已经尝试四处寻找这种情况,并且大多数似乎是使用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;

The problem is that when you realloc() and increase the allocated memory size, the new memory is not initialised (or with a debug library, initialised to a sentinal value).问题是,当您realloc()并增加分配的内存大小时,新内存未初始化(或使用调试库初始化为一个标记值)。 So, assuming you know the oldSize , a quick fix is:所以,假设你知道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;

Now, according to the realloc() definition , when you call:现在,根据realloc()定义,当您调用时:

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

It behaves as:它的行为如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM