【问题标题】:Run-Time Check Failure #2 - Stack around the variable was corrupted运行时检查失败 #2 - 变量周围的堆栈已损坏
【发布时间】:2012-10-08 15:21:06
【问题描述】:

我已经在 stackoverflow 看到了一些问题,但没有一个问题能解决我的问题...

我在 C 中有该代码:


#include <stdio.h>
#include <stdlib.h>

int main ()
{
    char str[] = "";
    scanf("%[^\n]", str);
    printf("Você digitou: %s\n", str);
    system("pause");
}

当我运行程序时,我遇到了错误:

运行时检查失败 #2 - 变量“str”周围的堆栈已损坏。

现在,我真的不知道我在那里做错了什么...... :(

【问题讨论】:

    标签: c


    【解决方案1】:

    数组str 在初始化的情况下只能保存一个char。对scanf() 的调用将覆盖str 的边界,从而导致未定义的行为,在这种情况下会破坏堆栈。您需要确定str 数组的大小并限制读取的字符数以防止缓冲区溢出。

    要使用scanf(),请指定要读取的最大字符数:

    char str[1024];
    if (1 == scanf("%1023[^\n]", str)) /* Check return value to ensure */
    {                                  /* 'str' populated.             */
    }                                  /* Specify one less than 'str'  */
                                       /* size to leave space for null.*/
    

    您也可以使用fgets(),但之后需要删除换行符。

    【讨论】:

      【解决方案2】:

      您不应该用用户输入覆盖常量。将char str[] = "" 替换为char * str = malloc(&lt;enough bytes for any possible input),甚至了解更安全的API。

      【讨论】:

        【解决方案3】:

        您只分配一个字节来存储输入。线

        char str[] = "";
        

        为字符串内容分配零字节,为其空终止符分配一个字节。相反,做类似的事情

        char str[100];
        

        或任何最大输入长度。

        【讨论】:

          【解决方案4】:

          此答案适用于所有从 Java/C# 或其他现代面向对象语言转向 C++ 的人。

          对我来说,这个问题发生的原因如下:

          我创建了自己的自定义 C++ 类。

          MyClass.h

          class MyClass {
          
          public:
              void work();
          
          };
          

          MyClass.cpp

          #include "MyClass.h"
          #include <iostream>
          
          class MyClass{
              int64 propA, propB;
          
              public:
                  void work();
          
          };
          
          void MyClass::work() {
              // some work that uses propA and propB
          }
          

          我的直觉是 propApropB 将只是私有属性,在此类之外的代码中是不可见的。

          问题原来是我没有把propApropB放在MyClass.h里。 当MyClass 被调用者实例化时,编译器不知道它应该分配多少内存。

          我只是将属性添加到标题MyClass.h

          MyClass.h(固定)

          class MyClass {
              int64 propA, propB;
          
          public:
              void work();
          
          };
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2010-09-21
            • 2013-12-13
            • 2013-12-10
            • 2015-02-09
            • 2015-05-24
            • 2021-12-31
            • 2014-10-20
            • 2014-07-01
            相关资源
            最近更新 更多