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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With