gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 23:51:15 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com