問題 :
在用VS2008寫一段代碼,算法都沒有問題,但是調試的時候發現出了main之后就報 Stack around the variable 'xxx' was corrupted 的錯誤,后來發現是數組越界造成的。測試下面類似情形的代碼:
- #include <iostream>
- using namespace std;
- int main()
- {
- int i, j, tmp;
- int a[10] = {0};// 0, 1, ... , 9
- for(i = 0; i < 10; ++i)
- {
- a[i] = 9 - i;
- }
- for(j=0; j<=9; j++)
- {
- for (i=0; i<10-j; i++)
- {
- if (a[i] > a[i+1])// 當j == 0時,i會取到,導致a[i+1]越界
- {
- tmp = a[i];
- a[i] = a[i+1];
- a[i+1] = tmp;
- }
- }
- }
- for(i=1;i<11;i++)
- {
- cout << a[i]<<endl;
- }
- system("pause");
- return 0;
- }
出現下圖 Debug Error:
Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted
原因 :
Stack pointer corruption is caused writing outside the allocated buffer in stack memory.
解決方法 :
This kind of error is detected by setting /RTC1 compiler option from menu 屬性頁(Alt+F7) -> 配置屬性 -> C++ -> 代碼生成 -> 基本運行時檢查
有以下幾個選項:
(1) 默認值
(2) 堆棧幀 ( /RTCs )
(3) 未初始化的變量 ( /RTCsu )
(4) 兩者 ( /RTC1, 等同與 /RTCsu )
(5) <從父級或項目默認設置繼承>
方法1 :修改數組越界的錯誤。
方法2 :設置為 (1) 默認值,就不再進行 stack frame run-time error checking。
Using /RTC1 compiler option enables stack frame run-time error checking. For example, the following code may cause the above error messge.
- #include <stdio.h>
- #include <string.h>
- #define BUFF_LEN 11 // 12 may fix the Run-Time Check Failure #2
- int rtc_option_test(char * pStr);
- int main()
- {
- char * myStr = "hello world";
- rtc_option_test(myStr);
- return 0;
- }
- int rtc_option_test(char * pStr)
- {
- char buff[BUFF_LEN];
- strcpy(buff, pStr); //cause Run-Time Check Failure #2 - Stack around
- //the variable 'buff' was corrupted.
- return 0;
- }
參考 :
Stack around the variable was corrupted 解決方案
http://laokaddk.blog.51cto.com/368606/238718
stack around the variable was corrupted
http://www.cnblogs.com/hxf829/archive/2009/11/28/1659749.html
