运行时检查失败#2 – 变量周围的堆栈已损坏
我已经在stackoverflow上看到了一些问题,但没有一个问题解决了我的问题……
我在C中有这样的代码:
#include #include int main () { char str[] = ""; scanf("%[^\n]", str); printf("Você digitou: %s\n", str); system("pause"); }
当我运行该程序时,我有错误:
运行时检查失败#2 – 变量’str’周围的堆栈已损坏。
现在,我真的不知道我在那里做错了什么…… 🙁
数组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()
但之后需要删除换行符。
您不应该使用用户输入覆盖常量。 用char * str = malloc(
char str[] = ""
,或者甚至学习更安全的API。
您只需分配一个字节来存储输入。 这条线
char str[] = "";
为字符串内容分配零字节,为其空终止符分配一个字节。 相反,做一些类似的事情
char str[100];
或者无论最大输入长度是多少。
这个答案适用于从Java / C#或其他一些现代面向对象语言来到C ++的每个人。
对我来说,这个问题发生的原因如下:
我创建了自己的自定义C ++类。
MyClass.h
class MyClass { public: void work(); };
MyClass.cpp
#include "MyClass.h" #include class MyClass{ int64 propA, propB; public: void work(); }; void MyClass::work() { // some work that uses propA and propB }
我的直觉是propA
和propB
只是私有属性,从这个类之外的代码propB
不到。
问题是我没有将propA
和propB
放在MyClass.h
。 当MyClass
被调用者实例化时,编译器不知道它应该分配多少内存。
我只是将属性添加到标头MyClass.h
:
MyClass.h(已修复)
class MyClass { int64 propA, propB; public: void work(); };