问题描述
我已经在嵌入式Linux中使用malloc()分配了内存(大约10 MB).并检查了空闲内存为67080 kB,但是即使使用free()释放了内存之后,它仍然保持不变.只有在应用程序终止后,内存才可以再次使用. free()不会使释放的内存对系统可用,如果可以的话,如何使它可用.
I have allocated memory using malloc() in embedded Linux (around 10 MB). And checked the free memory it was 67080 kB but even after freeing it using free() it remains the same. It is only after the application is terminated the memory is available again. Does free() not make the freed memory available to the system, if so how to make it available.
推荐答案
不,通常不是.malloc()通常通过低级sbrk()
或mmap()
调用从OS请求内存.一旦分配给应用程序,free()只会将内存返回到属于该应用程序的内存池.也就是说,它不会返回给操作系统以供另一个进程使用. (尽管在某些情况下可以使用一些启发式方法.)
No, usually not.malloc() normally requests memory from the OS by the low level sbrk()
or mmap()
call. Once assigned to the application, free() just returns the memory to a memory pool that belongs to the application. That is, it's not returned back to the OS for use in another process. (Though some heuristics are in-place to do so in certain circumstances).
如果交换空间到位,那么问题就不大了,操作系统将交换出应用程序未使用的内存,为所需的其他物理内存腾出空间.
If swap space is in place, this becomes less of a problem, the OS will swap out the unused memory of applications to make room for additional physical memory that's required.
退出应用程序.
或者您将需要编写自己的内存分配器来做到这一点(通常情况下,这不是一件容易的事,尤其是如果您不想牺牲开销和速度的话).
Or you would need to write your own memory allocator that could do this.(which in the general case is not an easy task especially if you don't want to sacrifice overhead and speed).
对于一个相对较大的10MB内存,您可以简单地使用mmap()
请求匿名内存,并且当您munmap()
该内存时,该内存将被释放回操作系统.
For a relatively big single piece of 10MB, you could simply request anonymous memory with mmap()
and the memory will be released back to the OS when you munmap()
that piece of memory.
这篇关于free()不释放嵌入式Linux中的内存.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!