【发布时间】:2015-01-15 20:23:00
【问题描述】:
是否可以在函数结束后强制程序释放函数期间分配的内存?
我的情况基本上是这样的。我有一个 for 循环,它调用另一个函数并做一些事情然后返回。这个其他函数(下面代码中的 myfunction)然后调用我无法控制的函数(下面代码中的 otherpersonsfunction)。每次我的程序调用 otherpersonsfunction 时,内存使用量都会增加并且不会下降。如果仅调用 otherpersonsfunction 一次或两次,这不是问题,但如果 myvector 变得非常大,那么我将多次调用它(足以导致运行它的服务器至少一次耗尽内存)。我无法更改 otherpersonsfunction 的工作方式,所以我想知道的是,一旦调用完成,是否可以强制程序清除调用 myfunction 期间分配的内存。我可以在 for 循环中放入什么东西来完成这个吗?
for(int j = 0; j < myvector.size(); j++)
{
//some code, then a function call
myfunction(myvector.field1);
//force program to free all memory allocated during execution of myfunction.
//How do I do this?
}
myfunction(myvector.field1)
{
//some code, then a function call
otherpersonsfunction(myvector.field1);
return;
}
【问题讨论】:
-
en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization 大致就是你想用谷歌搜索的东西。或等待第一个答案解释它:)
-
看不到样本中明确分配的任何内容?所以你可能根本不需要?
-
如果
otherpersonsfunction是导致内存增长的原因,那么如果没有修改代码的权限,您将无能为力。 -
@crashmstr 是的,我希望不会是这样。
-
在不知道真正的函数签名以及
otherfunction应该做什么的情况下,不可能知道这是否可以解决,或者您的代码或otherfunction中是否存在错误。otherfunction是否分配了您负责删除的内容?
标签: c++ memory memory-management