这个循环运行多少次?

时间:2022-06-16 02:21:14

Interview asked question:

采访问问题:

while(1)
{
void * a = malloc(1024*1024); 
}

How many times this loop will run on a 2 gb ram and a 8 gb ram ?

这个循环在2 gb ram和8 gb ram上运行多少次?

I said infinite loop because there is no terminating condition even if memory will be full. He din't agree.I don't have any idea now.Please help.

我说无限循环,因为即使内存已满,也没有终止条件。他不同意。我现在不知道。请帮忙。

1 个解决方案

#1


9  

It should run indefinitely. On most platforms, when there's no more memory available, malloc() will return 0, so the loop will keep on running without changing the amount of memory allocated. Linux allows memory over-commitment so that malloc() calls continue to add to virtual memory. The process might eventually get killed by the OOM Killer when the data that malloc() uses to administer the memory starts to cause problems (it won't be because you try using the allocated memory itself because the code doesn't use it), but Linux isn't stipulated as the platform in the question.

它应该无限期地运行。在大多数平台上,当没有更多可用内存时,malloc()将返回0,因此循环将继续运行而不会更改分配的内存量。 Linux允许内存过度使用,以便malloc()调用继续添加到虚拟内存。当malloc()用来管理内存的数据开始引起问题时,这个过程可能最终被OOM Killer杀死(这不是因为你尝试使用分配的内存,因为代码不使用它),但Linux没有被规定为问题中的平台。

#1


9  

It should run indefinitely. On most platforms, when there's no more memory available, malloc() will return 0, so the loop will keep on running without changing the amount of memory allocated. Linux allows memory over-commitment so that malloc() calls continue to add to virtual memory. The process might eventually get killed by the OOM Killer when the data that malloc() uses to administer the memory starts to cause problems (it won't be because you try using the allocated memory itself because the code doesn't use it), but Linux isn't stipulated as the platform in the question.

它应该无限期地运行。在大多数平台上,当没有更多可用内存时,malloc()将返回0,因此循环将继续运行而不会更改分配的内存量。 Linux允许内存过度使用,以便malloc()调用继续添加到虚拟内存。当malloc()用来管理内存的数据开始引起问题时,这个过程可能最终被OOM Killer杀死(这不是因为你尝试使用分配的内存,因为代码不使用它),但Linux没有被规定为问题中的平台。