我有一个函数,其中有一个空闲内存。
我想在调用这个函数后断言函数已经释放了给定的内存。
而且我无法更改此函数中的任何内容。
我需要它来进行 uni 测试。我想测试我的函数,我想检查我的函数在调用后是否真的释放了内存
问题在代码中
void func(char *mem)
{
// Some where in the function there is a free of the memory
// The free could be into if condition so there is a risk to not be executed
}
int main()
{
char *mem = malloc(20);
func(mem);
// how to assert here that the memory is freed?
}
最佳答案
简短的回答:没有办法实现。
确保释放的内存不会被意外重新使用或确定某些指针已释放的通常方法是在释放后立即将其设置为 NULL。为此,在您的示例中,您需要更改 func()
。如果您不能对 func()
进行任何更改,那么就无法确定传递给它的指针是已释放还是仍然有效。
此外,如果您的 func() 将为某些调用释放内存而不为其他调用释放内存,那么这是一个糟糕的设计。必须有更好、更透明的方法来管理动态分配的内存。
关于c++ - 如何断言内存已释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198028/