-4
dict[num] = malloc(INIT);
奇怪的malloc崩潰問題
assert(dict != NULL);
如果字典是char**
,而INIT是10在崩潰的時候,字典**有80個內存realloced到它,這應該周邊足夠20串],num是15在崩潰期間
我使用malloc一個奇怪的情況
malloc(25)
=全功能運行正常
malloc(17-24)
=斷言錯誤 - 線2
malloc(anything <=16)
=在第1行
如果有幫助崩潰,dict[num]
應該保持2個字符,字母(或換行),數字,和一個nullbyte。 dict[15]
恰好是'\ n0'。
這是怎麼發生的?我以爲你只需要分配與字符一樣多的內存。
對於記錄,我還有一個memset(dict[num],'\0',INIT)
行,發生在malloc + assert行之後。
EDIT =這裏的整個功能 - 它應該是一個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;
}
你能粘貼一個sscce嗎? – Bathsheba
什麼是'num'? – Evert
什麼是sscce?如後 –