c++ - 如何解决堆栈 "smashing detected"

标签 c++

我写了一个非常简单的 C++ 程序来生成随机字符串。在执行以下代码时,它会给出“检测到堆栈粉碎”。

#include<bits/stdc++.h>
#define SIZE 30
using namespace std;

int main() {
    srand(time(0));
    string str;
    int len = rand() % SIZE;
    for(int i = 0; i < len; i++) {
        str[i] = (char)((rand() % 26) + 'a');
    //      cout<<str[i];
    }
    cout<<str<<endl<<"..."<<endl<<len<<endl;
}

最佳答案

当您初始化字符串时,它的大小为 0

string str;

因此你做的任何作业都是越界的

str[i] = ...

知道长度后需要调整字符串的大小

int len = rand() % SIZE;
str.resize(len);

关于c++ - 如何解决堆栈 "smashing detected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57006188/

相关文章:

c++ - 如果在森林中发出 Qt 信号,而周围没有人听到它,它会发出声音吗?

c++ - 回调函数和常规函数有什么区别?

c++ - 额外的数字被附加到字符串,不知道为什么?

c++ - COM SDK 引用文档应该用什么语法编写?

python - 如何编译多个 C++ 文件以将它们与 Python ctypes 一起使用?

c++ - 如何动态创建相关类型?

c++ - OpenCV 在调整大小功能时崩溃

C++ 包含类的排序列表

c++ - 什么时候在 OOP 中使用友元是谨慎的?

c++ - 您可以在 autoexp.dat 预览中使用连续的 #if block 吗?