gpt4 book ai didi

c - 奇怪的 malloc 崩溃问题

转载 作者:行者123 更新时间:2023-11-30 21:20:55 25 4
gpt4 key购买 nike

dict[num] = malloc(INIT);

assert(dict != NULL);

其中 dict 是 char** ,并且 INIT 为 10 [在崩溃时,dict** 重新分配了 80 block 内存,这应该足以容纳大约 20 个字符串],崩溃期间 num 为 15

我在使用 malloc 时遇到了一个奇怪的情况

malloc(25) =整个函数运行良好

malloc(17-24) = 断言错误 - 第 2 行

malloc(anything <=16) = 在第 1 行崩溃

如果有帮助,dict[num]应该保存 2 个字符、一个字母(或换行符)、一个数字和一个空字节。 dict[15]恰好是“\n0”。

为什么会发生这种情况?我认为你只需要分配与字符一样多的内存。

根据记录,我还有一个 memset(dict[num],'\0',INIT) malloc + 断言行之后出现的行。

编辑=这是整个函数 - 它应该是一个 LZ78 压缩器/编码器

char *factory(char *input,int max){
int j,k,match,subtractor=0;
char *x = malloc(INIT);

char **dict = malloc(10*sizeof(dict[0]));
int dict_size = INIT;
assert ( dict != NULL );

char *temp = malloc(INIT);
int temp_size = INIT;
assert ( temp != NULL );

char *factors = malloc(INIT);
assert ( factors != NULL );
char *tempstring = malloc(INIT);
int tempstr_size = INIT;
assert ( tempstring != NULL );

int dlen = 1;

int dmax = 1;
factor_t *factorstr = malloc(INIT);
int break2 = 0;
memset(dict,'\0',INIT);
dict[0] = "";
x = input;

char unmatched[2];
unmatched[1] = '\0';
while(strlen(x)){
match = 0;
memset(temp,'\0',temp_size);
if (dlen>INIT){
temp_size = temp_size + dlen;
temp = realloc( temp, temp_size );
assert( temp != NULL );
}
printf("DMAX = %d\n",dmax);
if (dmax==dict_size){
dict_size *= 2;
dict = realloc(dict, dict_size*sizeof(*dict));
assert(dict != NULL);
}

for(j=0;j<dlen;j++){
if (dlen > strlen(x)){
dlen = strlen(x) - 1;
printf("\nRunning out of space! DLEN = %d\n",dlen);
}
memset(temp,'\0',temp_size);
strncpy(temp, &x[0], dlen-j);

for(k=0;k<dmax;k++){
if (strcmp(temp,dict[k])==0){
if ((strlen(temp)+1)>(tempstr_size)){
tempstr_size += strlen(temp) + 1;
tempstring = realloc( tempstring , tempstr_size);
assert( tempstring != NULL );
}
unmatched[0] = x[dlen-j];
memset(tempstring, '\0', tempstr_size);
strcat(tempstring,temp);
strcat(tempstring,unmatched);
dict[dmax] = malloc(strlen(tempstring)+100);
assert ( dict[dmax] != NULL ) ;
strcpy(dict[dmax], tempstring);
dmax++;
match = 1;
subtractor = dlen-j;
if (!j){
dlen++;
}
break2 = 1;
break;
}
}
if (break2){
break2=0;
break;
}
}
if (!match){
unmatched[0] = x[0];

factorstr[dmax].c = unmatched[0];
factorstr[dmax].k = 0;

dict[dmax] = malloc(INIT);
assert ( dict[dmax] != NULL );

memset(dict[dmax],'\0',INIT);
strcpy(dict[dmax],unmatched);
printf("dict dmax = %s\n",dict[dmax]);
dmax++;
subtractor = 1;
}
x = x + subtractor;
}
return 0;

}

最佳答案

memset(dict,'\0',INIT);

这是一个错误,没有任何意义。 dict 是一个指向指针数组的指针。它不是字符串,也没有大小 INIT

关于c - 奇怪的 malloc 崩溃问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com