VS2008中Run-Time Check Failure #2 - Stack around the variable 'xxx' was corrupted 錯誤解決方法


問題

在用VS2008寫一段代碼,算法都沒有問題,但是調試的時候發現出了main之后就報 Stack around the variable 'xxx' was corrupted 的錯誤,后來發現是數組越界造成的。測試下面類似情形的代碼:

  1. #include <iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.     int i, j, tmp;   
  6.     int a[10] = {0};// 0, 1, ... , 9   
  7.     for(i = 0; i < 10; ++i)  
  8.     {  
  9.         a[i] = 9 - i;  
  10.     }  
  11.     for(j=0; j<=9; j++)   
  12.     {   
  13.         for (i=0; i<10-j; i++)  
  14.         {  
  15.             if (a[i] > a[i+1])// 當j == 0時,i會取到,導致a[i+1]越界  
  16.             {   
  17.                 tmp = a[i];   
  18.                 a[i] = a[i+1];   
  19.                 a[i+1] = tmp;  
  20.             }   
  21.         }  
  22.     }   
  23.     for(i=1;i<11;i++)   
  24.     {  
  25.         cout << a[i]<<endl;  
  26.     }  
  27.     system("pause");  
  28.     return 0;  
  29. }   

出現下圖 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.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #define BUFF_LEN 11 // 12 may fix the Run-Time Check Failure #2  
  4. int rtc_option_test(char * pStr);  
  5. int main()  
  6. {  
  7.     char * myStr = "hello world";  
  8.     rtc_option_test(myStr);  
  9.     return 0;  
  10. }  
  11. int rtc_option_test(char * pStr)  
  12. {  
  13.     char buff[BUFF_LEN];  
  14.     strcpy(buff, pStr); //cause Run-Time Check Failure #2 - Stack around  
  15.     //the variable 'buff' was corrupted.  
  16.     return 0;  
  17. }  

   

參考
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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM