2012-05-09 57 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

我想在这种情况下完成输出以证明正确的空闲()。即使我不打算写很长的帖子。 –