C++ Change Max RAM Limit

对着背影说爱祢 提交于 2019-12-05 20:42:09
Sebastian

Do you allocate the objects on the stack and are in fact hitting the stack limit?

Do you, e.g., write something like this:

void SomeFunction() {
    MyObject aobject[100000];
    // do something with myobject
}

This array will be allocated on the stack. A better solution -- which automates heap allocation for you -- would be to write

void SomeFunction() {
    std::vector<MyObject> veccobject(100000); // 100.000 default constructed objects
    // do something with myobject
}

If for some reason, you really want a bigger stack, consult your compiler documentation for the appropriate flag:

How to increase the gcc executable stack size?

Can you set the size of the call stack in c++? (vs2008)

And you might want to consider:

When do you worry about stack size?

Do you understand why you are hitting the RAM limit? Are you sure that you don't have memory leaks (if you do have leaks, you'll need more and more RAM when running your application for a longer time).

Assuming a Linux machine, you might use valgrind to hunt and debug memory leaks, and you could also use Boehm's conservative garbage collector to often avoid them.

If these limits are being imposed on you by the system administrator, then no - you're stuck. If you're ulimiting yourself, sure - just raise the soft and hard limits.

As pointed out by Chris in the comments, if you're a privileged process, you could use setrlimit to raise your hard limit in process. However, one presumes if you're under a ulimit, then you're unlikely to be a privileged process.

If you have permissions you can use the setrlimit call (which supersedes vlimit) to set the limits at the start of your program. This will only affect this program and its offspring.

#include <sys/time.h>
#include <sys/resource.h>

int main() {
  struct rlimit limit;
  limit.rlim_cur = RLIM_INFINITY;
  limit.rlim_max = RLIM_INFINITY;
  if (0 != setrlimit(RLIMIT_AS, &limit)) {
  //errro
  } 
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!