Stack and Heap Space for Modern Computers

蓝咒 提交于 2019-12-01 23:03:55

This is all Win32-specific (not really C-specific, all just OS 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 .

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.

There is a philosophy that when you need to ask these kinds of questions, for practical and not educational or informational reasons, then you are doing something seriously wrong.

If you are asking this for error-checking or to make sure your program has enough memory, ect... then don't wrorry about it, seriously. As for your programs memory, you can use the task manager (on windows) if this is just for debugging. If you need to know this in your program, I wouldn't count on any non-hacky solution.

Abstractions for a reason Really, your program shouldn't have this as a concern. It is an OS concern, your problem should just be efficient with what it needs and let the OS do its job.

If you insist, you could look into /proc/meminfo, brk(), getrlimit() and setrlimit() (here are some docs) with the RLIMIT_STACK and RLIMIT_DATA values for approximations and rough-ishes.

#include <sys/resource.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main (int argc, char *argv[])
{
  struct rlimit limit;

  /* Get the stack limit. */
  if (getrlimit(RLIMIT_STACK, &limit) != 0) {
    printf("getrlimit() failed with errno=%d\n", errno);
    exit(1);
  }

  printf("The stack soft limit is %llu\n", limit.rlim_cur);
  printf("The stack hard limit is %llu\n", limit.rlim_max);
  exit(0);
}

Modified from here also see man getrlimit on your system

If you state what and why you want to do this, someone may have a better method or way of doing what you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!