How malloc call managed by user-library. I need the explanation of "How memory is being allocated in user space when malloc is called. Who manage it. Like sbrk() is called to enter in kernel space".
The malloc() package of functions manages the space. It obtains relatively large chunks of memory from the system using sbrk() and passes out smaller chunks to its callers as requested, using whichever of the many possible algorithms it is designed to use. The free() function places released memory back into its list of 'available for use' memory. Very seldom does it actually release memory back to the operating system itself.
There are many articles on the design of different versions of malloc(). There are many debugging versions of malloc(), in particular, which look for abuses of the allocated memory. You can read about memory allocation in Knuth 'The Art of Computer Programming'; it's in volume 1 in my memory serves.
The C runtime library manages the heap. The heap has some preallocated free store. If the runtime can't find a contiguous block there it tries to request more memory from the operating system - calls sbrk()
.
If the latter fails "out of memory" is reported - malloc()
returns a null pointer. If additional memory is requested successfully and the received chunk is bigger that what the malloc()
caller asked for the block in chunk is divided - one part is marked as occupied and returned to the caller and the other one is added to the free store.
From the point when sbrk()
returned successfully the memory chunk belongs to the calling program address space.