Memory management is a service provided by underlying operating system. When we call malloc()/free()
and there's no operating systems running(for example a bare metal embedded system), how is the memory allocation and tracking handled?
There should be an entity that tracks which addresses are free and which are not. That's OS memory management unit. malloc()/free()
will then have to call OS system calls. So no OS means no malloc()/free()
. Am I wrong in assuming this?
Update:
All answers pointed out that malloc/free
can use either static pool allocation(when no OS is available) or use sbrk/brk
which are kernel system calls. Question is how does the malloc/free
knows if there's a kernel beneath or not?
Answer(see comment by "Kuba Ober" under his answer below):
malloc doesn't need to know anything, because the C library that you link your project with is specific to the target: if you develop for Linux, you use a C library for Linux, different than when you develop for OS X, or Windows, or bare bones ARM Cortex M0. Or, heck, barebones x86. It's people who write the C library that know how to implement it so that it works on the desired target. For example, a barebones C library for x86 would use EFI and ACPI to query the list of available blocks of RAM unused by hardware nor BIOS, and then use those in fulfilling allocation requests.
There should be an entity that tracks which addresses are free and which are not.
There is. If there is no OS you'd have to handle this yourself.malloc
andfree
make use of OS memory manager. Typically on start the program allocate some memory from process heap and manage it to small chunks upon program request. On a bare metal system the C library must manage the whole pool of device memory.malloc
functions.malloc