2015-11-27 42 views
0

我想有一個函數,分配一個複雜的雙數組,執行一些操作,並返回計算出的最後一個值。雖然計算很好,但我在嘗試釋放分配的空間時遇到了問題。在執行過程中,我得到了「雙重釋放或內存損壞」的錯誤。我正在使用標準庫。使用免費()與動態分配的複雜指針

這裏是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <complex.h> 
#include <assert.h> 

double complex main() 
{ 
    // Declare fixed number of steps. 
    int number_of_elements=10; 
    // Reserve memory for array. 
    double complex *complexArray = calloc(number_of_elements,sizeof(double complex)); 
    // Verify if allocation was successfull. 
    assert(complexArray!=NULL); 
    // Fill first position with number and start counting 
    complexArray[0]=1+2*I; 
    int i=0; 
    for (i=0;i<number_of_elements;i++) 
    { 
     complexArray[i+1]=2*complexArray[i]; // Simple operation 
     printf("The complex number stored in position %i is %f+i%f\n\n",i+1,creal(complexArray[i+1]),cimag(complexArray[i+1])); // Print the current number 
    } 
    double complex output=complexArray[i]; 
    assert(complexArray!=NULL); // Check if pointer is not NULL again 
    free(complexArray); // Program fails here 
    complexArray=NULL; 
    return output; 
} 

我從「雙情結」改變了數據類型「雙」和它的作品。有什麼方法可以釋放複雜的數組嗎?

回答

4

你在分配的內存後面寫了。最後一個循環迭代使用i=9並寫入complexArray[i+1],這不在您分配的範圍內。 free()本身似乎沒有任何問題。例如

這樣的問題應該可以用valgrind來發現。

0

你的免費()關於雙複雜* complexArray = calloc()看起來是正確的。請記住,數組是從0開始的0,請仔細檢查索引,具體如下:

complexArray [i + 1] = 2 * complexArray [i]; //操作簡單

因爲這將導致第一輸出爲:保存在位置1

複數我想你的循環可能會拋出一個EXC_BAD_ACCESS的方式。