none
VS2017堆栈溢出异常 RRS feed

  • 问题

  •     各位技术大牛们好,我在写栈时发生了堆栈溢出的异常,但代码在Dev-C++ 5.11版本下可正常运行,请问是怎么回事?

        以下代码:

    #include<stack>
    #include<cstdio>
    #include<algorithm>
    const int M = 100001;
    using namespace std;
    int main()
    {
    	int n;
    	while (~scanf("%d", &n) && n)
    	{
    		stack<int>s;
    		long long sum = 0;
    		int h[M], l[M], r[M];
    		s.push(0);
    		for (int i = 1; i <= n + 1; i++)
    		{
    			if (i <= n)
    				scanf("%d", &h[i]);
    			else
    				h[i] = 0;
    			l[i] = r[i] = i;
    			while (s.size() > 1 && h[s.top()] >= h[i])
    			{
    				r[s.top()] = i - 1;
    				s.pop();
    			}
    			l[i] = s.top();
    			s.push(i);
    		}
    		for (int i = 1; i <= n; i++)
    			sum = max(sum, (long long)(r[i] - l[i] * h[i]));
    		printf("%lld\n", sum);
    	}
    	return 0;
    }

    2018年8月22日 4:02

全部回复

  • 你好,

    感谢在微软论发贴

    >>  各位技术大牛们好,我在写栈时发生了堆栈溢出的异常,但代码在Dev-C++ 5.11版本下可正常运行,请问是怎么回事?

    通常不建议在堆栈上使用非常大的数组,因为非常容易导致堆栈溢出问题,建议在堆上通过动态分配来放置大数组,这样会好点,示例如下。

    #include "stdafx.h"
    #include<stack>
    #include<cstdio>
    #include<algorithm>
    
    const int M = 100001;
    using namespace std;
    
    int main()
    {
    	//int a[M];
    
    	int* a = new int[M];
    
        return 0;
    }

    Best wishes,

    Jack Zhang




    MSDN Community Support&lt;br/&gt; Please remember to click &amp;quot;Mark as Answer&amp;quot; the responses that resolved your issue, and to click &amp;quot;Unmark as Answer&amp;quot; if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact &lt;a href=&quot;mailto:MSDNFSF@microsoft.com&quot;&gt;MSDNFSF@microsoft.com&lt;/a&gt;


    2018年8月22日 8:15
    版主