Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve stack "smashing detected"

Tags:

c++

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;
}
like image 921
Raja Sharma Avatar asked Nov 26 '25 18:11

Raja Sharma


1 Answers

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);
like image 187
Cory Kramer Avatar answered Nov 29 '25 06:11

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!