C-检查当前可用的可用RAM? [英] C - Check currently available free RAM?
问题描述
我知道如何使用malloc()
和free()
分配内存,但是还有一个标准的C函数来检查剩余的内存量,因此我可以定期调用以确保我的代码没有内存泄漏?
I know how to use malloc()
and free()
to allocate memory, but is there also a standard C function to check how much memory is left, so I can call that periodically to make sure my code has no memory leaks?
我唯一想到的就是无限循环地调用malloc(1)
,直到返回错误为止,但是不应该有一种更有效的方法吗?
The only thing I can think of is calling malloc(1)
in a endless loop until it returns an error, but shouldn't there be a more efficient way?
推荐答案
不,没有标准的C函数可以做到这一点.您可以使用某些特定于平台的功能来执行某些类型的查询(例如工作集大小),但是这些功能可能无济于事,因为有时正确地free()
d的内存仍然被认为是由以下人员分配的: OS,因为malloc
实现可能会将释放的内存保留在池中.
No, there's no standard C function to do that. There are some platform-specific functions you can use to perform certain types of queries (like working set size), but those probably won't be helpful, because sometimes memory which has been properly free()
d is still considered to be allocated by the OS because the malloc
implementation might keep the freed memory around in a pool.
如果您要检查内存泄漏,我强烈建议您使用 Valgrind 之类的工具,该工具可以在虚拟机,可以跟踪内存泄漏以及其他功能.
If you want to check for memory leaks, I highly recommend using a tool like Valgrind, which runs your program in a virtual machine of sorts and can track memory leaks, among other features.
如果您在Windows上运行,则可以使用 _CrtSetDbgFlag
检查内存泄漏.
If you're running on Windows, you can use _CrtDbgReport
and/or _CrtSetDbgFlag
to check for memory leaks.
这篇关于C-检查当前可用的可用RAM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!