Explore the mysteries of heap memory release in Linux operating system-Linux general technology-Linux programming and kernel information. The following is a detailed description. This morning, I got some tips from this version and finally learned about the mysteries of heap memory release. I would like to share it with you!
How does a Linux User process release memory?
The basic process of using memory for Linux processes:
(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // tech.ccidnet.com/pub/attachment/2006/9/843487.gif'); ">
We can see that the heap of the process is not directly based on the memory allocation policy of the Linux kernel, instead, it is built on the heap management policy of glibc (that is, the dynamic memory allocation policy of glibc). The heap management is implemented by glibc. Therefore, when we call free to release the memory obtained by malloc, instead of directly releasing the memory to the operating system, we return the heap management entity of glibc, glibc will make some optimizations in the policy of returning the actual physical memory to the system, so as to optimize the dynamic memory allocation process of user tasks.
So when will the glibc heap manager return the physical memory to the system?
It starts from the maximum linear address of the heap, and calculates the number of idle heap memory (until the heap memory address in use) of the user task from the back to the front. For example, in this figure:
(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // tech.ccidnet.com/pub/attachment/2006/9/843489.gif'); ">
It will think that there is a k releasable memory, only when the value is greater than a specific threshhold (2.3.6 is 64 k), it will return the memory to the system. The "UNUSED" memory in the middle will not be returned to the system, so the system cannot reuse this physical memory page (we assume that the system does not have the swap zone and swap file ), that is to say, the system memory will be reduced for this purpose. Unless the previous heap memory is released with free, glibc's heap manager may (but may) return the memory to the system.
Therefore, we should be careful when using malloc/free, especially when a lot of memory is allocated during initialization, but after that, we no longer need so much memory, this memory does not reach the threshhold value or some memory is not released at the highest linear address of the heap, but all the heap memory in front of it is released. In this case, user Tasks will waste some physical memory, which is intolerable in embedded systems with tight resources.