stack overflow c++

。_饼干妹妹 提交于 2019-12-02 10:45:28

Root Cause:

As you guessed correctly, the stack is limited and seems your allocation is large enough to be catered through it. This is not an language syntax error so it does not warrant a compilation error but it results in a run time exception thus causing a crash.

Solution 1:

You can make the array global, the allocation of an global array is not on stack so it should work fine for you:

int a [200000];

int main()
{
   .....
}

Solution 2:

You could use a std::vector

Solution 3:

You can use dynamic allocation through new.

Statement int a [200000]; attempts to allocate more memory on the stack than will fit, which caused stack overflow. Some people recommend that arrays larger than a few kilobytes should be allocated dynamically instead of as a local variable. Please refer to wikipedia: http://en.wikipedia.org/wiki/Stack_overflow#Very_large_stack_variables

3 changes I can see.
1 - allocating on the stack more than the stack can handle.
2 - k should always pointing to the next free space so you need to update than increase it.
3 - the index are starting from "0" both for the "q" for.

Fixed code:

#include <iostream> 

using namespace std;

int a [200000];

int main (){
    int n;
    int x;
    int k = 0; // счетчик для рабочего массива
 scanf("%d\n",&n);   

 for (int i = 0; i< n; ++i){
     std::cin >> x;
     if (x > 0)
     {
             a[k] = x;
             k++; //<< change 1
     }
     else if (x == 0)
     {
         for (int q = 0; q <= k; ++q) //<<change 2
         { // копирование 
             a[k+q] = a[q];
         }
         k *= 2;
     }
     else 
     {
         printf("%d %d\n",a[k],k);
         k--;
                        }
 }
 system("pause");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!