2016-11-20 74 views
1

我有這樣的代碼裏面一個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 ... 
+0

不要投malloc的 - 見http://stackoverflow.com/questions/605845/do-i-cast-the-結果是malloc –

+0

這行代碼如果(NULL ==(*(partial_results +(count-1))=(bignum_t *)malloc(sizeof(bignum_t)))){'試圖做太多走。 ' –

+2

'if(count == 1){ count2 = 0; } else { count2 = count-1; 「我喜歡它! – wildplasser

回答

0

對於此行:

/*the next malloc is the one that fails*/ 
    if(NULL==(*(partial_results+(count-1))=(bignum_t*)malloc(sizeof(bignum_t)))){ 
     return NULL; 
    } 

在任何情況下:

count需要是1 <= count <= long_op2。如果超出這個範圍,那麼你會得到未定義的結果。我看不到count的初始化,但是您應該在每個malloc之前輸出值count

這只是一個猜測,但我懷疑你的真正用意是:

partial_results[i]=(bignum_t*)malloc(sizeof(bignum_t)); 
+0

對不起,我沒有評論這個計數,它從值1開始(因此第一個位置count-1 = 0),並且它在9結束(所以最後的位置將是8)。我確實打印出來瞭解價值。不,如果我使用[i],我從8開始,首先我要寫0的位置,這就是爲什麼我使用count-1。 –

+0

因此,而不是'count',使用'long_op2 - 1 - i'作爲索引值。 – selbie

+0

我試過了,同樣的錯誤。 –