I wrote a very simple c++ program to generate random string. And while execute the following code it gives 'stack smashing detected'.
#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;
}
When you initialize your string, it has a size of 0
string str;
Therefore any assignment you do is out of bounds here
str[i] = ...
You need to resize your string after you know the length
int len = rand() % SIZE;
str.resize(len);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With