Richard T Slade
Richard T Slade

Reputation: 35

Segmentation fail for arrays

I've been scratching my head all day trying to work out why these two arrays produce a segmentation fault.

I can comment out one and the program runs but using both at same time causes it to crash. Could they be overlapping in memory?

I'm clueless, any help would be appreciated.

#include <iostream>

int main()
{

    int y = 3823;
    int x = 10;
    int z = 64;

    double foo[y][x];
    double bar[y][z];

    foo[2][2] = 0;
    bar[2][2] = 2;

    std::cout << foo[2][2] << std::endl;
    std::cout << bar[2][2] << std::endl;

    return 0;
}

Upvotes: 1

Views: 46

Answers (2)

zwol
zwol

Reputation: 140445

This program does not crash when I run it (with both arrays uncommented).

This program requires more than 2,263,216 bytes of stack just to enter main. It is most likely that your OS does not provide this much stack by default. You can probably raise the limit, but without knowing what OS you are on, I cannot tell you precisely how.

Upvotes: 3

Joe Z
Joe Z

Reputation: 17926

You're trying to allocate around 2 megabytes on the stack. That's a lot of memory.

You should consider some form of dynamic allocation that doesn't allocate these arrays on the stack.

Upvotes: 4

Related Questions