values of array gets changed automatically after taking string input

509 views Asked by At
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    long int m,i;
    cin>>m;
    float first=0,second=0,disp=0;
    int arr[m];
    char ch[m];
    for(i=0;i<m;i++)
    {
    cin>>arr[i];
    }
    cout<<" before="<<arr[0]<<endl;
    cin>>ch;
    cout<<" after="<<arr[0]<<endl;
    //puts(ch);
    return 0;
}

First i insert elements in an array then Print the zeroth index of an array after that i take string input .Suddenly what happened!. My zeroth index of array got changed!!!. How it's possible ,Would anyone care to explain this

output of a program in c++

values of the arr[0] got Changed, why?

2

There are 2 answers

10
Barmar On BEST ANSWER

The problem is that you input too many characters for cin >> ch;. Since m == 40, you declared it as char ch[40]. This allows you to enter 39 characters (not 40 because of the trailing '\0' character), but you entered much more than that, so it wrote outside the array boundary, which results in undefined behavior. In this case, it overflowed into the arr array.

I suggest you use std::string rather than a char array, then it will automatically expand to the proper size.

0
Rares On

You have stumbled upon a Buffer Overflow. Wikipedia has a basic example, as well as more details on this subject. (Read more)

It's what happens when you overrun the ch array's boundary and write to it's adjacent memory locations (which in this case happened to be the arr array).