I allocated a large array on the stack after adjusting the stack size using setrlimit. When this array is declared in main() and then passed as argument to a method, I get a segmentation fault. When the array is declared as a local variable inside a method, the code runs without any seg fault. I am running the code on an Amdx86-64 linux box with 8GB RAM.
#include <iostream>
#include <sys/resource.h>
using usll = unsigned long long;
void sumArray0();
double sumArray1(double c[], usll dim);
int main(int argc, char* argv[])
{
const rlim_t stackSize = 3 * 1024UL * 1024UL * 1024UL;
struct rlimit rl;
int result;
printf("The required value of stackSize is %lu\n", stackSize);
result = getrlimit(RLIMIT_STACK, &rl);
if (result == 0)
{
if (rl.rlim_cur < stackSize)
{
rl.rlim_cur = stackSize;
result = setrlimit(RLIMIT_STACK, &rl);
if (result != 0)
{
fprintf(stderr, "setrlimit returned result = %d\n", result);
}
else
{
printf("The new value of stackSize is %lu\n", rl.rlim_cur);
}
}
}
// // This seg faults
// const usll DIM = 20000UL * 18750UL;
// double c[DIM];
// for (usll i{}; i<DIM; ++i)
// {
// c[i] = 5.0e-6;
// }
// double total = sumArray1(c, DIM); // Seg fault occurs here
sumArray0(); // This works
std::cout << "Press enter to continue";
std::cin.get();
return 0;
}
void sumArray0()
{
double total{};
const usll DIM = 20000UL * 18750UL;
double c[DIM];
for (usll i{}; i<DIM; ++i)
{
c[i] = 5.0e-6;
}
for (usll i{}; i<DIM; ++i)
{
total += c[i];
}
std::cout << "Sum of the elements of the vector is " << total << std::endl;
}
double sumArray1(double c[], usll dim)
{
double total{};
for (usll i{}; i<dim; ++i)
{
total += c[i];
}
return total;
}
My questions are:
Why am I getting a stackoverflow in the first case?
Is it because a new chunk of memory is requested in the call to the method sumArray1()?
Isn't the array accessed via a pointer when passed as argument to the method?
As recommended here, Giant arrays causing stack overflows, I always use std::vector and never allocate large arrays on the stack to prevent issues like above. I will highly appreciate it if anyone knows of any tweaks, tricks or workarounds that can make the call to sumArray1() work.