我在使用setrlimit调整堆栈大小后,在堆栈上分配了一个大型数组。当该数组在main()函数中声明并作为参数传递给一个方法时,会导致段错误。如果将数组声明为方法内部的局部变量,则代码可以运行而不会出现段错误。我在一台8GB RAM的Amdx86-64 Linux计算机上运行这段代码。
#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;
}
我的问题是:
为什么在第一种情况下会出现堆栈溢出?
是因为调用sumArray1()方法时请求了一块新的内存块吗?
当将数组作为参数传递给该方法时,不是通过指针访问数组吗?
如此推荐,巨大的数组引起堆栈溢出,我总是使用std::vector并且永远不会在堆栈上分配大型数组,以防止出现上述问题。如果有人知道可以使调用sumArray1()方法正常工作的任何技巧、诀窍或解决方法,我会非常感激。
std::vector
更快,一旦数据量足够大,它只会引起问题,就像您现在遇到的一样。 - NathanOliverstd::vector
呢?毕竟你知道它肯定能工作。 - NathanOliver