将大堆栈分配的数组作为函数参数传递会导致堆栈溢出

问题描述 投票:1回答:1

我使用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;
}

我的问题是:为什么在第一种情况下会出现stackoverflow?是否是因为在对方法sumArray1()的调用中请求了新的内存块?作为参数传递给方法时,不是通过指针访问数组吗?

按照这里的建议Giant arrays causing stack overflows,我总是使用std :: vector,并且从不在堆栈上分配大数组以防止出现上述问题。如果有人知道可以使对sumArray1()的调用起作用的任何调整,技巧或变通办法,我将非常感激。

我使用setrlimit调整了堆栈大小后,在堆栈上分配了一个大数组。当此数组在main()中声明,然后作为参数传递给方法时,出现分段错误。当...

c++ arrays linux c++17 stack-overflow
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.