stackoverflow上的回答:
In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is, that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided of course, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason of course is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 Bytes eg. 4KB).
So returning 40 Bytes to the OS will just not work. So what does free do?
Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have of course some administrative data in the beginning. This is also the reason, why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.
The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger then the needed memory, it is just divided into two parts. One is returned to caller, the other is put back into the free list.
There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list -- for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.
首先malloc()/free()的操作取决于操作系统和编译器的实现。一般来说当你调用malloc(),系统会从堆中给你分配一块足够大的空闲内存,并返回指向它的指针,并且标记它不再空闲。当调用free(),系统检查这块内存的大小,并把它加入到free列表中,而不是立即回收它的内存,因为操作系统只能处理特定大小且连续的内存块:一般来说是512Bytes的倍数。Free内存块链表的另一个作用是,当调用malloc()时,系统会首先从这个表中查找符合要求的内存块,如果找不到适合大小的内存块再向操作系统申请新的内存空间。