Yahoo Interview Question
SDE1sCountry: India
Interview Type: In-Person
On 32 bit os, process can access virtual memory which is available upto 4GB and it is independent of RAM. So, process can allocate 600mb dynamic memory even ram is of 500mb.
if 500 mb is the ram size then definitely you might have set your virtual memory space as 4 times of that and in that case you might encounter page faults but if you are restricted only within this 500 mb of size what you can do is that in your program write your own memory handler function which will not allow you to do so. Or else you can refer external sorting methodology in this regard and please check how it gets solved there.
malloc returns successfully only when it allocates the required amount of memory , so how is it possible that it allocates 600 mb at a time without having a RAM of suuficient size...
@shadyabhi... as you said, Lazy allocation means to allocate the memory when it is required, so the remaining part of the 600mb data will be stored in external storage. but Heap is used for malloc and the heap resides in physical memory, so how is it possible for malloc to return true as it will not have sufficient heap memory.
Are we sure on this?
Virtual memory surely allows to load bigger programs into memory, but the malloc allocates a new memory of the needed size frm the heap for the program, and it will not succeed
Static allocation wil be successful, but dynamic runtime allocation I believe will fail.
NO! Heap is large because process memory is large!!! It is from virtual memory!!!!!!!!!!!!!!!!!!!
Malloc will allocate the memory size of 600MB because malloc calls sbrk and brk for getting the free chunk of memory. sbrk allocates free chunk from system memory, also malloc deals with paged virtual system and as rightly pointed out using lazy memory allocation it can be done.
stackoverflow.com/questions/5716100/what-happens-in-the-kernel-during-malloc
stackoverflow.com/questions/6988487/what-does-brk-system-call-do
:brk calls heap which is in VM so so problem allocating till VM is available :)
The memory will be allocated according to the virtual memory available for the process & that can be higher (and is usually higher) than the RAM available on the system.
- shadyabhi July 23, 2013So, your program won't fail and the memory will be allocated. There is a thing called lazy allocation which means that the memory is actually not allocated until it's actually used.