我写了一个非常简单的 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/