在while循环中调用函数()是否在每次循环迭代时使用内存

Does a function() call in a while loop uses memory everytime the loop iterate?

本文关键字:循环 迭代 内存 while 调用 函数 是否      更新时间:2023-10-16

我是新来的,我目前正在学习如何用c++编程。

所以我的问题是:每次循环迭代时,while循环内的函数调用是否都会消耗内存?

的例子:

int count = 0;
while (count < 10)
{
    function_call(); // Will this consume 10x more memory?
    ++count;
}

No。__

你调用你的函数10次,所以你的函数使用的内存被使用了10次。但是这个函数只有在执行结束后才会被再次调用,所以无论它使用了什么资源都已经被释放了。

所以最后,它使用了相同数量的内存,只是保存时间延长了10倍。

†:这是假设你的函数没有泄漏内存。

任何未释放的手工分配的内存都将被使用。如果你的函数泄漏了N个字节,那么这个循环将泄漏10乘以N个字节。但希望你没有泄露任何信息。;)

这个问题是模棱两可的,因为c++有两种类型的内存,动态和自动(通常称为堆和堆栈),它们具有不同的特征。

int count = 0;
while (count < 10) {
   function_call(); // Will this consume 10x more memory?
   ++count;
}

1)这会消耗10倍多的自动内存吗?

答案是否定的。自动内存在范围进入时分配,并在范围退出时释放。对function_call()的循环重复调用将每次调用都"重新开始"。


2)这会消耗10倍多的动态内存吗?

答案-不知道你提供的。

如果function_call()不使用动态内存

NO - a) if function_call()"使用"有限的动态内存通过new(), and获得B)在返回之前使用delete释放所有的动态内存。

NO - a)如果function_call '使用'获得的有限动态内存使用new(),和B)一个different_function_call适当地释放内存。

    Research term for you: object lifetime.  Some dynamic memory
    needs to exists longer than the lifetime of the function_call.
    Several other answers mentioned 'memory leaking'.  I consider this a 
    coding error, and thus not relevant to your question.

Yes - a)如果function_call '使用'获得的有限动态内存使用new(),和B)没有其他代码发布它,并且C)包含function_call的进程不终止。

     On most OS's, terminating the process in which this code runs will 
     cause the release of all dynamic memory (and other resource) back
     to the OS's control, and no longer accessible to the terminated 
     process (or any other process in the form created).
     If it is possible that this process can run until dynamic memory is 
     exhausted, I think what happens next is UB (undefined behavior).