c - 为什么我不能释放内存?

标签 c structure

我用C写了一个简单的计数器结构:

typedef struct{
    int value;
}Counter;

然后,我写了一些简单的实现:

void createCounter(Counter *dCount)
{ 
    dCount = (Counter*)malloc(sizeof(Counter));
    dCount->value = 0;
}

void FreeResource(Counter *dCount)
{
  free(dCount);
}

现在主要是,我想释放我创建的指针,它提示说被释放的指针没有分配。我正在查看代码,我想我在调用 createCounter() 函数时为它分配了内存?

 int main()
  {
    Counter m;
    CreateCounter(&m);
    FreeResource(&m); //run time error given here..

    return 0;
 }

最佳答案

您正在尝试传递在堆栈中分配的变量的地址,然后尝试将 malloc 分配给它的地址分配给它,这不会反射(reflect)在调用者中。因此,当您尝试释放它时,您实际上是在将堆栈变量的地址传递给 free,因此您会得到未定义的行为。

改变功能

void createCounter(Counter *dCount) 
{      
    dCount = (Counter*)malloc(sizeof(Counter));    
    dCount->value = 0; 
} 

作为

void createCounter(Counter **dCount) 
{      
   *dCount = (Counter*)malloc(sizeof(Counter));     
   (*dCount)->value = 0; 
} 

在您的情况下,指针按值传递,新的内存地址分配不会反射(reflect)在调用者中。

主要功能必须更改为:

int main()     
{       
  Counter *m;       
  CreateCounter(&m);       
  FreeResource(m); //run time error given here..          
  return 0;    
}   

关于c - 为什么我不能释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11688288/

相关文章:

c - 这是使用数组未定义行为吗?

C程序错误: expected expression before int

c - 如何安全地将 for 循环与内部的 memcpy 并行

c++ - 从 C 或 C++ 中的函数返回多个数据项

c++ - 结构、数组、函数

c - 了解 C 中的结构填充

c - 使用 C 的套接字和线程

c - 为什么我的 if 语句不起作用?

java - 如何在Java中创建和显示列表?

python-3.x - 构建由 3 个子程序组成的程序的正确方法