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仍然认为是由操作系统分配的,因为 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 上运行,则可以使用 _CrtDbgReport
和/或 _CrtSetDbgFlag
检查内存泄漏.
If you're running on Windows, you can use _CrtDbgReport
and/or _CrtSetDbgFlag
to check for memory leaks.
这篇关于C - 检查当前可用的可用 RAM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!