Program 8-4

Post date: Apr 10, 2013 7:51:18 AM

Program 8-4

1 // This program unsafely stores values beyond an array's boundary.

2 // What happens depends on how your computer manages memory.

3 // It MAY overwrite other memory variables. It MAY crash your computer.

4 #include <iostream>

5 using namespace std;

6

7 int main()

8 {

9 const int SIZE = 3;

10 int A[SIZE] = {1, 1, 1}; // Define A as a 3-element int array

11 // holding the values 1, 1, 1

12 int B[SIZE]; // Define B as another 3-element int array

13

14 // Here is what is stored in array A

15 cout << "Here are the original numbers in 3-element array A: ";

16 for (int count = 0; count < 3; count++)

17 cout << A[count] << " ";

18

19 // Attempt to store seven numbers in the 3-element array

20 cout << "\n\nNow I'm storing 7 numbers in 3-element array B.";

21 for (int count = 0; count < 7; count++)

22 B[count] = 5;

23

24 // If the program is still running, display the numbers

25 cout << "\nIf you see this message, the computer did not crash.";

26 cout << "\n\nHere are the 7 numbers in array B : ";

27 for (int count = 0; count < 7; count++)

28 cout << B[count] << " ";

29

30 cout << "\nHere are the numbers now in array A: ";

31 for (int count = 0; count < 3; count++)

32 cout << A[count] << " ";

33

34 return 0;

35 }

Program Output

Here are the original numbers in 3-element array A: 1 1 1

Now I'm storing 7 numbers in 3-element array B.

If you see this message, the computer did not crash.

Here are the 7 numbers in array B : 5 5 5 5 5 5 5

Here are the numbers now in array A: 5 5 5