gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:05:46 25 4
gpt4 key购买 nike

我用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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com