Answer the question
In order to leave comments, you need to log in
How does the operating system understand how much memory needs to be cleared?
char *array = malloc(256);
...
free(array); //!
Answer the question
In order to leave comments, you need to log in
Not 256 bytes are allocated, but a service structure + 256 bytes (and with page addressing, at least 1 page is allocated in general). It is in this service structure that information about the block itself is stored in front of the selected block.
How does the operating system understand how much memory needs to be cleared?
No way. She's purple. But your program is another matter.
now the compiler knows that array is 256 bytes
and here the compiler will substitute the address of the variable and its size into the cleanup code.
And free() does not mean at all that the OS will free the memory.
On the contrary - most likely the memory will remain with your program.
https://learnc.info/c/memory_allocation.html
well, about the same as she understands that the memory is already occupied (allocated).
table is probably.
Fact 1. malloc and free are not implemented by the OS, but by the C/C++ runtime library. Yes, of course, from time to time the runtime library makes system calls in order to get the address space from the OS, but this is not done for every malloc / free.
Fact 2. You need to clearly understand that you are working with the language tools and the standard library of the language, and not the OS. If on some device a compiled C program must work without an OS, then the ways to implement the malloc / free functionality will be different.
Fact 3. Algorithms that implement the work of malloc and free store quite a lot of service information for themselves, in particular, the size and position of the allocated blocks. You don't have direct access to this information, but that doesn't mean it doesn't exist. It is enough at least to allocate new blocks to you and correctly release the old ones. Such algorithms are called memory managers . By the way, in this simple article on the wiki it is written about the so-called hierarchy of memory managers. If you familiarize yourself with this concept, you will probably learn more than from all the answers combined.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question