Question

How does actually malloc get the present free memory space available in the microcontroller. Does it keep a list of areas unallocated continously in the runtime? How does it get information of a previous malloc assignment memory allocation if there are two malloc statements in the code

How can one know which memory is free and which one is not at runtime. At compilation time we can know which all locations in RAM is assigned by the compiler for the variable. Does malloc uses this information to do this.

Was it helpful?

Solution

As the commentators said above, there are multiple implementations of malloc and the algorithm may vastly vary for each of these implementations. This is a vast and complicated area and you should read up on the memory management to get a complete idea on the topic.

In simple words, all the malloc implementations are backed up by the kernel's memory management schemes. The kernel see the whole system memory as pages for fixed size (4k, 8k etc) and all the allocations and frees are done on the pages. There will be a memory management subsystem exists for all the kernel implementations and which does the accounting of whole memory allocations and frees happening on the system. When you call a malloc, it will eventually reaches this memory management subsystem, and looks for the next available free page from the pool and allocates for the requesting process. Before giving the page to the requester, he will make sure to mark it as used and same way when you free up the memory it will add it back to the free pool and unmark used. There exists so many implementations on how the kernel does all these effectively (read up on memory manager implementations in linux)

In common implementations, there exists a minimal memory manager functionality in the userspace itself. The user space process itself maintains a free pool and when a malloc requests memory, before breaking in to kernel, it will look in its own free pool if memory is available. If available it will mark it up and satisfies the request without the help of kernel. Similarly, when you free up the memory, the freed up chunk of memory will not immediately go back to kernel's free pool instead it will stay with the process's free pool so that next malloc can use this.

As I said in the beginning, this is a huge and complicated topic and you can find a lot of documentations available in the internet about this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top