我如何找出在Linux上的GNU C ++中剩下多少可用内存 [英] How do I find out how much free memory is left in GNU C++ on Linux

查看:157
本文介绍了我如何找出在Linux上的GNU C ++中剩下多少可用内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个C ++程序(使用gcc编译并在RedHat Linux上运行)。程序需要在运行时知道堆栈上剩余多少空间以及堆中剩余多少空间。我意识到可能没有一个明确的答案这个问题(关于堆),因此,或者,我可以使用已从堆分配的内存量而不是。是否有一个库/系统函数调用,将给我这个数据?

I'm writing a C++ program (compiled with gcc and running on RedHat Linux). The program needs to know at runtime how much space is left on the stack and how much is left in the heap. I realize there may not be a definite answer to this question (about the heap), so alternatively, I could use the amount of memory already allocated from the heap instead. Is there a a library/system function call that will give me this data?

我想补充一点,我只需要这个调试目的,只需要粗略的估计,所以快速和脏的解决方案是完全可以接受的。但是,我需要频繁地查询内存使用情况,因此不能接受Unix cmd-line实用程序并解析其输出。

I'd like to add that I only need this for debugging purposes, and only need rough estimates, so quick-and-dirty solutions are perfectly acceptable. However, I need to query the memory usage very frequently, so shelling out to a Unix cmd-line utility and parsing its output is not acceptable.

推荐答案

您可能可以创建自己的新和删除函数,封装真正的新操作符和删除操作符,并同时记下内存使用情况。

You probably can create your own new and delete functions that encapsulates the real new and delete operators and take note of the memory usage at the same time.

对于堆栈,C中有一个小技巧,你可以看一下在当前函数中定义的第一个局部变量的地址,来了解堆栈指针在哪里。我想它应该在C ++中工作,但还没有尝试过。

For stack, there's a trick in C where you take a look at the address of the first local variable defined in your current function to get a rough idea about where the stack pointer is at the moment. I guess it should work in C++ but haven't tried it.

这篇关于我如何找出在Linux上的GNU C ++中剩下多少可用内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆