Visual studio stack overflow when defining variables (c++)

1

I've been trying to solve a competition problem in the style of the link below using c++ (the actual problem that I'm trying to solve isn't available for the public)

http://orac.amt.edu.au/cgi-bin/train/problem.pl?set=aio18int&problemid=1032

I have written a C++ program in Visual studio that attempts to solve it, but when I run this code: (there are some includes for and but I couldn't get the formatting).

    int main() 
{
int n = 1;

freopen("pairin.txt", "r", stdin);


scanf("%d", &n);

int s[200005];
for (int i = 0; i < 2 * n; i++)
{
    scanf("%d", &s[i]);
}

int d[100005];
for (int i = 0; i < n; i++) {
    d[i] = -1;
}

for (int i = 0; i < n; i++) {
    if (d[s[i] - 1] == -1) {
        d[i] == s[i];
    }
    else {
        d[i] = i - d[i];
    }
}

int max = 0;
for (int i = 0; i < n; i++) {
    if (d[i] > max) {
        max = d[i];
    }
}

freopen("pairout.txt", "w", stdout);
printf("%d", max);

return 0;
}

It returns the error: Unhandled exception at 0x00B11CC9 in a.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00402000). occurred

Visual studio then opens up a tab of an asm file called chkstk.asm for whatever reason.

I have an idea of when this error occurs normally, but what seemed to be triggering it was defining "int n = 1;" when I stepped through with the debugger, which absolutely boggles my mind. All I want to do is debug my algorithm, not trying to get int n = 1; to work.

I'm using Visual Studio 2017, with the _CRT_SECURE_NO_WARNINGS flag enabled.

I tried this in an online IDE (commenting out all the IO lines) and main() returned 0 just fine.

visual-studio
visual-c++

1 Answer

1

The reason of the problem is in s and d array definitions. These variables are allocated on stack. Occuped space is more than 1Mb, but default stack size in Visual Studio is 1Mb:

/F Sets the program stack size in bytes. Without this option the stack size defaults to 1 MB.

So you are run out of stack space.

To fix the problem you should increase stack size or allocate memory on heap or reduce array size (e.g. int s[100000]; and int d[50000];).

answered on Stack Overflow Nov 24, 2018 by Nikita • edited Nov 24, 2018 by Nikita

User contributions licensed under CC BY-SA 3.0