现代计算机的堆栈空间 [英] Stack and Heap Space for Modern Computers

查看:78
本文介绍了现代计算机的堆栈空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用C编写时,如何确定启动程序时内存中有多少堆栈空间可用?堆空间如何?

When writing in C, how can I tell how much stack space is available in memory when I launch a program? How about heap space?

如何知道程序执行期间正在使用多少内存?

How can I tell how much memory is being used during the execution of my program?

推荐答案

这是所有Win32特定的(不是真正的C特定的,仅是OS API):

This is all Win32-specific (not really C-specific, all just OS API):

创建线程时,默认情况下它会获得1MB的堆栈空间,可以在您使用的任何CreateThread API中对其进行修改.

When a thread is created, it gets 1MB stack space by default, by that can be modified in whatever CreateThread API you use.

您可以查看线程信息块以查找实际的堆栈信息,但是即使有文档记录,也未正式支持此技术,请参见

You can peek into the thread information block to find the actual stack info, but even though this is documented, this technique isn't officially supported, see http://en.wikipedia.org/wiki/Win32_Thread_Information_Block .

另外,对于32位应用程序,您最多只能寻址2GB,因此对于设计使用大量内存的应用程序,要注意的是进程的虚拟地址空间的总大小(已提交+保留),其中包括所有堆分配.您可以使用GlobalMemoryStatusEx API以编程方式访问该进程的虚拟内存,请查看 ullTotalVirtual 参数用于虚拟地址空间.一旦您的进程接近1.8或1.9GB的VAS,堆分配和VirtualAlloc调用就会开始失败.对于普通"应用程序,您不必担心VAS即将用尽,但是检查失败分配始终是一件好事.另外,除非有错误或设计错误,否则不应引起堆栈溢出.

Also, for a 32-bit application, you can only address up to 2GB, so for an app that by design uses lots of memory, then the thing to watch out for is the total size of the process' virtual address space (committed + reserved), which includes all heap allocations. You can programmatically access the process' virtual memory with the GlobalMemoryStatusEx API, look at the ullTotalVirtual param for virtual address space. Once your process gets close to 1.8 or 1.9GB of VAS, then heap allocations and VirtualAlloc calls begin to fail. For "normal" apps, you don't have to worry about running out of VAS, but it's always good to check for fail allocs. Also, you shouldn't get a stack overflow, unless you have a bug, or a bad design.

这篇关于现代计算机的堆栈空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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