C - 释放指向指针的指针

标签 c pointers malloc free

<分区>

在我的代码中,我分配了一些我需要释放的二维数组。然而,每当我认为我已经掌握了指针的概念时,它们总是让我感到惊讶,因为它们没有按照我的期望去做;)

那么谁能告诉我如何处理这种情况?:

这就是我为指针分配内存的方式:

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 ) 之后添加调试语句表明这段代码实际上是有效的,我的问题出在其他地方。谢谢你时间!

乔纳斯

最佳答案

代码没问题。我试过运行它并且运行良好。下面是我测试的代码(我用 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;
}

并输出:

adnan@adnan-ubuntu-vm:desktop$ ./a.out 
allocatingi
Allocation complete. Now deallocating
complete without error

关于C - 释放指向指针的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10513326/

相关文章:

c - realloc() 结构数组的旧大小无效

c - 编译器生成的汇编文件中的 "#APP"是什么意思?

c++ - 从其他人内部调用 C 包装函数

c++ - 在一个范围内推送五个对象指针,然后检查对象的 bool 是否为 false,会出错

c - 指针类型转换

c - 需要关于在 C 中实现 malloc 和 free 的建议

c - ‘{’ token c 程序之前的预期表达式

连续字符串

c - 指针改变变量的值

c - 内存分配的间隔