Reputation: 510
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;
}
Upvotes: 2
Views: 1345
Reputation: 117886
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);
Upvotes: 4
Reputation: 11168
str[i] = (char)((rand() % 26) + 'a');
str
has not yet allocated any data, so this is undefined behaviour. use str +=
instead.
Upvotes: 4