2012-05-09 59 views
4

在我的代碼中,我分配了一些我需要釋放的二維數組。然而,每一次我想我已經掌握了指針的概念時,他們不斷通過沒有做什麼,我希望他們奇怪我;)C - 釋放指針指針

因此,誰能告訴我如何處理這種情況?:

我這是怎麼分配內存的指針我:

typedef struct HRTF_ { 
    kiss_fft_cpx freqDataL[NFREQ] 
    kiss_fft_cpx freqDataR[NFREQ] 
    int nrSamples; 
    char* fname; 
} HRTF; 

HRTF **_pHRTFs = NUL; 
int _nHRTFs = 512; 

_pHRTFs = (HRTF**) malloc(sizeof(HRTF*) *_nHRTFs); 

int i = _nHRTFs; 
while(i > 0) 
    _pHRTFs[--i] = (HRTF*) malloc(sizeof(HRTF)); 

// Load data into HRTF struct 

這裏就是我想我應該釋放使用的內存:

if(_pHRTFs != NULL) 
{ 
    __DEBUG("Free mem used for HRTFs"); 
    for(i = 0; i < _nHRTFs; ++i) 
    { 
    if(_pHRTFs[i] != NULL) 
    { 
     char buf[64]; 
     sprintf(buf, "Freeing mem for HRTF #%d", i); 
     __DEBUG(buf); 
     free(_pHRTFs[i]); 
    } 
    } 
    __DEBUG("Free array containing HRTFs"); 
    free(_pHRTFs); 
} 

解放了個人_pHRTFs[i]的作品,最後__DEBUG聲明被打印,但最後的free(_pHRTFs)給我一個分段錯誤。爲什麼?

沒關係 - 添加調試語句之後的最後free(_pHRTFs)表明,這種代碼就是工作,我的問題出在其他地方..感謝您的時間!

喬納斯

+3

該代碼看起來沒問題。你真的可以評論分配和免費之間的一切,看看它是否還在發生? – cnicutar

+0

如何使用char * fname?如果你爲它分配內存,你應該釋放它,然後釋放擁有結構的數組。 –

+0

代碼看起來不錯 - 請不要在C代碼中輸入malloc的結果 - 這不是必要的,並且可以掩蓋編譯器警告可能會顯示的錯誤 –

回答

2

代碼是好的。我試過運行它,它工作正常。下面是我測試的代碼(我用int替換了未知的數據類型)和輸出結果,這表明這裏沒有任何錯誤。你得到的錯誤是因爲別的。

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

typedef struct HRTF_ { 
     int freqDataL[10]; 
     int freqDataR[10]; 
     int nrSamples; 
     char* fname; 
} HRTF; 

HRTF **_pHRTFs = NULL; 
int _nHRTFs = 512; 

int main(){ 
    printf("allocatingi\n"); 
    _pHRTFs = (HRTF**) malloc(sizeof(HRTF*) *_nHRTFs); 

    int i = _nHRTFs; 
    while(i > 0) 
      _pHRTFs[--i] = (HRTF*) malloc(sizeof(HRTF)); 

    printf("Allocation complete. Now deallocating\n"); 
    for(i = 0; i < _nHRTFs; ++i) 
    { 
     if(_pHRTFs[i] != NULL) 
     { 
      char buf[64]; 
      sprintf(buf, "Freeing mem for HRTF #%d", i); 
      //__DEBUG(buf); 
      free(_pHRTFs[i]); 
     } 
    } 
    printf("complete without error\n"); 
    return 0; 
} 

輸出:

[email protected]:desktop$ ./a.out 
allocatingi 
Allocation complete. Now deallocating 
complete without error 
1

內存分配和釋放似乎罰款。我也編譯了上面的代碼,將類型更改爲int後,我得到了下面的輸出。問題在於別的地方。

Freeing mem for HRTF #0 
Freeing mem for HRTF #1 
...... 
Freeing mem for HRTF #509 
Freeing mem for HRTF #510 
Freeing mem for HRTF #511 
+0

請編輯您的答案,檢查是否可以縮短輸出。 – tuxuday

+0

我想在這種情況下完成輸出以證明正確的空閒()。即使我不打算寫很長的帖子。 –