问题
:
在用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