简体   繁体   中英

Why does this c++ program cause a system crash?

#include <iostream>
using namespace std;

int main()
{
  int nums[20] = { 0 };
  int a[10] = { 0 };

  cout << a << endl;
  cout << nums << endl;

  cout << "How many numbers? (max of 10)" << endl;
  cin >> nums[0];
  for (int i = 0; i < nums[0]; i++)
  {
     cout << "Enter number " << i << endl;
     cin >> a[i];
  }
  // Output the numbers entered
  for (int i = 0; i < 10; i++)
        cout << a[i] << endl;
  return 0;
}

If this program is run and we enter 255 for how many numbers, and 9 for every single number, it causes it to crash.

Its because int a[10] = { 0 }; and you try to index it past the 10th cell or location 9. You need to fix your for loop

  for (int i = 0; i <  nums[0]; i++)
  {
     cout << "Enter number " << i << endl;
     cin >> a[i];
  }

or change the length of your cell in intialization

Why does your program crash? You've only allocated 10 elements for a .


You tell the user "(max of 10)" . The user ignores this and types in 255 . You need to check that the user has listened to your warning before doing anything else.

cout << "How many numbers? (max of 10)" << endl;
cin >> nums[0];

// Has the user listened to your warning?
if (nums[0] > 10) {
    cout << "Bad input!" << endl;
    return 0;
}

You are using nums[0] as the max bound for the loop

  for (int i = 0; i < nums[0]; i++)
  {
     cout << "Enter number " << i << endl;
     cin >> a[i];
  }

In your case you are doing 255 loops and in each iteration you add the value into a[i] .

You declared the array a to have a size of 10 elements, but you are trying to add 255 elements.

This is the issue. The size of a needs to be the same of the max bound value of the main loop ( nums[0] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM