[CPP]Why the active solution configuration "debug" in Visual Studio can make some error?

-1

Excuse me, my primary language isn`t English.

I wrote a recursion function to resolve the "Queens Problem".

int* Queen_Recursion(int n,int nowRow = 1, int nowColumn = 1, int* map = nullptr)
{
    if (map == nullptr)
        map = new int[n + 1]{0};
    if (nowRow > n)
    {
        std::cout << "No." << ++map[0] << " Answer:";
        for (int i = 1; i < n + 1; i++)
            std::cout << '\t' << '(' << i << ", " << map[i] << ')';
        std::cout << std::endl;
        return Queen_Recursion(n, n, map[n] + 1, map);
    }
    else if (nowColumn > n)
    {
        if (nowRow == 1)
            return map;
        map[nowRow] = 0;
        return Queen_Recursion(n, nowRow - 1, map[nowRow - 1] + 1, map);
    }
    bool CanPlace = true;
    for (int i = 1; i < nowRow; i++)
        if (map[i] == nowColumn || i - nowRow == map[i] - nowColumn || i - nowRow == nowColumn - map[i])
            CanPlace = false;
    if (CanPlace)
    {
        map[nowRow] = nowColumn;
        return Queen_Recursion(n, nowRow + 1, 1, map);
    }
    else
        return Queen_Recursion(n, nowRow, nowColumn + 1, map);
}
int main()
{
    int* temp = Queen_Recursion(8);
    delete temp;
    return 0;
}

When I choose the "debug", it shows me only 5 answers.

enter image description here

When I choose the "Release", it shows me 92 answers. Certainly, it`s correct. enter image description here

Can someone tell me the reason?

By the way, I tried to set initial values of the "map", and I think there isn`t an out of bounds array access in this function.

Unhandled exception at 0x00007FF73D68298D in 04-Some Recursion Problems.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000FA88903EC0). occurred

c++
visual-studio
visual-studio-2019
asked on Stack Overflow Apr 27, 2020 by RabbitLime • edited Jun 20, 2020 by Community

1 Answer

0

Recursive functions like this function want a lots of stack. Your function called about 18000 times to solve your problem and it means the program need to keep 18000 functions stack.

Here is some tips for your code.

As errors shown your stack become full in your recursive call of your function.

As i see your value can't get higher than 8 ( Chess is 8*8 Square) You can change all the ints to uint8_t.

You can define variables like bool CanPlace outside of the function to reduce stack usage.

You can declear uint8_t i outside of your function, for your loop counter and this can help your program working better

Finally you need to resize your stack size of your project. The default stack size in Visual Studio is 1MB. you need to change it.

You can see THIS link to increase your stack size in visual studio.

answered on Stack Overflow Apr 27, 2020 by MH Alikhani • edited Apr 27, 2020 by MH Alikhani

User contributions licensed under CC BY-SA 3.0