2

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;
}
Raja Sharma
  • 460
  • 1
  • 7
  • 19
  • 1
    All containers (including `std::string`) are *empty* by default. Any indexing in them will be out of bounds and lead to undefined behavior. – Some programmer dude Jul 12 '19 at 11:36
  • 6
    Also please take some time to read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Some programmer dude Jul 12 '19 at 11:37
  • Change that line to `str.at(i) = (char)((rand() % 26) + 'a');` and the exception thrown will give you a big hint as to the answer your question. – PaulMcKenzie Jul 12 '19 at 13:14

2 Answers2

4
str[i] = (char)((rand() % 26) + 'a');

str has not yet allocated any data, so this is undefined behaviour. use str += instead.

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
4

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);
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218