Arrays 动态字符串数组中的分段错误
我有一个动态调整大小的字符串数组(我在编译时不知道字符串的大小),它一直给我一个分段错误。数组包含在名为Arrays 动态字符串数组中的分段错误,arrays,c,string,dynamic,Arrays,C,String,Dynamic,我有一个动态调整大小的字符串数组(我在编译时不知道字符串的大小),它一直给我一个分段错误。数组包含在名为hm的结构中,它有一个字符串数组和一个值数组。这部分代码仅用于在结构中添加新字符串时正确调整字符串数组的大小。 我对C和structs比较陌生,所以如果有更好的方法来实现这一点,我很想听听。我已经试过四处寻找这种情况,大多数人似乎都是使用sizeof(char)而不是sizeof(char*)来处理外部数组的问题,但是当我更改时,问题仍然发生 //problematic part of the
hm
的结构中,它有一个字符串数组和一个值数组。这部分代码仅用于在结构中添加新字符串时正确调整字符串数组的大小。
我对C和structs比较陌生,所以如果有更好的方法来实现这一点,我很想听听。我已经试过四处寻找这种情况,大多数人似乎都是使用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;
//函数中有问题的部分
char**t=(char**)realloc(hm->keys,hm->size*sizeof(char*);
如果(t)hm->keys=t;
对于(i=0;isize;i++){
char*temp=(char*)realloc(hm->keys[i],hm->largestKey*sizeof(char));//此处存在seg错误
如果(临时){
hm->键[i]=温度;
}
}
//结构
类型定义结构HM_结构{
大小;
最大键的大小;
字符**键;
int*值;
void(*添加)(结构HM_结构*HM,字符*键,int值);
}HM;
问题在于,当您realloc()
并增加分配的内存大小时,新内存没有初始化(或者使用调试库,初始化为sentinal值)。因此,假设您知道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;
其行为如下:
char* temp = malloc(hm->largestKey * sizeof(char));
在调用
realloc()
之前,您的代码会调用malloc()
或calloc()
,对吗?您不能在那里使用realloc()
,因为不是所有的hm->键[i]
都已初始化。您可以使用realloc()
用于重新分配键
数组中的元素,但必须使用malloc()
用于添加的新元素。这意味着您需要在增加数组之前保存旧大小。
char* temp = malloc(hm->largestKey * sizeof(char));