I am learning C++ and was given the task to create a program that allows user to modify an array with 10 integers in it. if user gives an index out of range program will exit. Program works with negative numbers and all numbers with in the range. when I enter a number like 10 which is above the range I get:
* stack smashing detected *: terminated
I am new to this and any help will be much appreciated.
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<int, 10> myData; // creates array size 10
int i = 0;
int v = 0;
for (unsigned int n = 0; n < myData.size(); n++) // makes all elements 1
{
myData[n] = 1;
}
do
{
for (unsigned int a = 0; a < myData.size(); a++)
{
cout << myData[a] << " ";
}
cout << endl << "Input index: ";
cin >> i;
cout << endl << "Input value: ";
cin >> v;
myData[i] = v;
} while (i >= 0 && i < myData.size());
{
cout << endl << "Index out of range: Exit " << endl;
}
return 0;
}
When I run the program, I get this:
1 1 1 1 1 1 1 1 1 1
Input index: 10
Input value: 4
Index out of range: Exit
*** stack smashing detected ***: <unknown> terminated
[1] 56 abort (core dumped) ./edit