问题
How would I change the max amount of RAM for a program? I constantly am running out of memory (not system max, ulimit max), and I do not wish to change the global memory limit. I looked around and saw the vlimit() function might work, but I'm unsure exactly how to use it.
Edit: I'm on linux 2.6.38-11-generic This is not a memory leak, I literally must allocate 100k of a given class, no way around it.
回答1:
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?
回答2:
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.
回答3:
If these limits are being imposed on you by the system administrator, then no - you're stuck. If you're ulimit
ing 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.
回答4:
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
}
}
来源:https://stackoverflow.com/questions/7997602/c-change-max-ram-limit