Reputation:
I wrote a C++ program in Ubuntu. In main function, I have 2-D array like this:
int main() {
unsigned long long int s[11000][100];
// some code to manipulate with s (just for initialization)
// ...
}
And the program failed to run. After search the web, I know that the size of 2-D array exceeds the default stack size in Ubuntu which is about 8 MB. I tried some suggests to change stack size automatically in my program. So I added some few lines of code:
int main() {
unsigned long long int s[11000][100];
const rlim_t kStackSize = 32 * 1024 * 1024;
struct rlimit rl;
int result;
result = getrlimit(RLIMIT_STACK, &rl);
if (result == 0) {
if (rl.rlim_cur < kStackSize) {
rl.rlim_cur = kStackSize;
result = setrlimit(RLIMIT_STACK, &rl);
if (result != 0) {
printf("error\n");
}
} else {
printf("error\n");
}
// some code to manipulate with s (just for initialization)
// ...
} // end main
But I still got the segmentation fault (core dumped) error. I also checked the stack size, its size is now 32 MB, 4 times lager than the size of 2-D array. Also try set stack size to RLIM_INFINITY, but failed again. Can anybody help me figure out the reason and the solution? Thank you so much!
Upvotes: 2
Views: 753
Reputation: 25647
Given the size of this block of memory, you should instead allocate it with either new[]
or malloc
and delete[]
or free
it as appropriate. Or, if you're using C++, you should use std::vector
or some other heap-allocated container.
The reason it is still crashing is because it's still trying to allocate more than some limit on the still-limited stack space, before you even try to adjust it. Variables in automatic storage (that is, on the stack) are allocated before the function executes.
Upvotes: 5