stack smashing detected error

Q.Basic structure program
Unable to find an error.
This error comes when running this program.
*** stack smashing detected ***: terminated
Can someone tell what's the problem in this program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
using namespace std;

int main()
{
    struct book{
        int roll ; char name[20] ; char add[20];
    };
    struct book b[2];
    int i;
    
    for(i=0;i<3;i++)
    {
        cout<<"Enter Roll, Name & Addess of student "<<i+1<<" : ";
        cin>>b[i].roll;
        cin>>b[i].name;
        cin>>b[i].add;
    }
    
    for(i=0;i<3;i++)
    {
        cout<<b[i].roll<<" ";
        cout<<b[i].name<<" ";
        cout<<b[i].add<<endl;
    }
    
    return 0;
}
What is the input you are giving the program?

Edit: Actually, aside from potential char array buffer overflows, your book b array is only size 2, but you are looping over it 3 times.

Change the '3' on lines 12 and 20 to '2', or better yet, make a constant int in like const int NumBooks = 2;

________________________

The more insidious problem is that you allow the user to potentially cause a buffer overflow because you are using cin >> into char arrays.
You should use std::strings instead, ideally.
1
2
3
4
5
    struct book {
        int roll;
        string name;
        string add;
    };


Or, if you must use char arrays because of some asinine professorial requirement, then use:
1
2
3
4
cin >> b[i].roll;
cin.ignore(); // ignore newline left in buffer from cin >> call.
cin.getline(b[i].name, 20);
cin.getline(b[i].add, 20);
Last edited on
>> doesn't allow 'white-space' to be entered (ie space, tab, newline). getline() does.

If you want to use >> with a c-style string, then also use setw() to set the input max.

[not tried]

1
2
cin>>setw(20) >> b[i].name;
cin>>setw(20) >> b[i].add;

Really very thank you for helping.
I'm a beginner & was doing a question from a book.
I got that the array size was 2 so was having the problem, I was confused by the accessing element with the size so was unable to find error.

Actually I am learning c before c++ and using c++syntax and compiler as c++ supports all c features. and I don't know about std::strings, const, but got this one cin.getline(b[i].name, 20);

Again really very thank you.


Last edited on
cin be C++, as is cout.
...
c would use scanf or scan something and printf.
structs also look rather different, and require a typedef.

you are headed down 1990's C with IOSTREAM style, which mixes C with C++ syntax to reduce the annoying stuff of C but without using the power of C++.
Last edited on
Topic archived. No new replies allowed.