我有這樣的代碼裏面一個malloc時出了問題,ç的malloc斷言
/*function starts*/
if(NULL==(partial_results=(bignum_t**)malloc(sizeof(bignum_t*)*long_op2))){
return NULL;
}
/*to initialize all the members of the array*/
for(i=0;i<long_op2;i++){
(*(partial_results+i))=NULL;
}
for(i=long_op2-1;i>=0;i--){
digit2=op2->digits[i]-48;
count++;
carry=0;
if(count==1){
count2=0;
}else{
count2=count-1;
}
/*the next malloc is the one that fails*/
if(NULL==(*(partial_results+(count-1))=(bignum_t*)malloc(sizeof(bignum_t)))){
return NULL;
}
/*after this the codes continues, but everything from here is ok an it isn't causing any problem*/
這裏的事情,我試圖創建long_op2元素的數組(9),所以在第一個malloc我創建了一個9 bignum_t指針數組。然後,在for內部,我嘗試爲數組的每個成員創建一個bignum_t結構。當long_op2小於或等於6時,我沒有問題,但是當它是7或更多時,第一個malloc(假設創建指針的那個malloc)不起作用。我發現了錯誤,
tp3: malloc.c:2372: sysmalloc: Assertion
的事情是,我不是要寫比創建數組的數量比較多,因爲數量到達8最大,如果long_op2是9,所以這是好。 另一件奇怪的事情是,當我使用Valgrind運行程序時,它確實有效!
PD:這是我的第一個問題,所以如果我犯了什麼錯誤,我很抱歉。
PD2:這是程序的工作方式。
980581618*215129902
long_op1 & long_op2 9 9
for with: i, count-1 8 0
doing malloc malloc done
for with: i, count-1 7 1
doing malloc malloc done
for with: i, count-1 6 2
doing malloc malloc done
for with: i, count-1 5 3
doing malloc malloc done
for with: i, count-1 4 4
doing malloc malloc done
for with: i, count-1 3 5
doing malloc malloc done
for with: i, count-1 2 6
doing malloc malloc done
for with: i, count-1 1 7
doing malloc malloc done
for with: i, count-1 0 8
doing malloc
tp3: malloc.c:2372: sysmalloc: Assertion ...
不要投malloc的 - 見http://stackoverflow.com/questions/605845/do-i-cast-the-結果是malloc –
這行代碼如果(NULL ==(*(partial_results +(count-1))=(bignum_t *)malloc(sizeof(bignum_t)))){'試圖做太多走。 ' –
'if(count == 1){ count2 = 0; } else { count2 = count-1; 「我喜歡它! – wildplasser