Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many times this loop will run?

Tags:

c

loops

memory

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 ?

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.

like image 515
joey rohan Avatar asked Aug 05 '13 07:08

joey rohan


1 Answers

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.

like image 165
Jonathan Leffler Avatar answered Oct 24 '22 02:10

Jonathan Leffler