Monday, January 11, 2010

Program 86: Lack of Self-Awareness













Program 86: Lack of Self-Awareness

The following program is designed to test out our simple array. Yet there's a problem that causes the program to fail in an unexpected way.




1 /************************************************
2 * array_test -- Test the use of the array class*
3 ************************************************/
4 #include <iostream>
5
6 /************************************************
7 * array -- Classic variable length array class.*
8 * *
9 * Member functions: *
10 * operator [] -- Return an item *
11 * in the array. *
12 ************************************************/
13 class array {
14 protected:
15 // Size of the array
16 int size;
17
18 // The array data itself
19 int *data;
20 public:
21 // Constructor.
22 // Set the size of the array
23 // and create data
24 array(const int i_size):
25 size(i_size),
26 data(new int[size])
27 {
28 // Clear the data
29 memset(data, '\0',
30 size * sizeof(data[0]));
31 }
32 // Destructor -- Return data to the heap
33 virtual ~array(void)
34 {
35 delete []data;
36 data = NULL;
37 }
38 // Copy constructor.
39 // Delete the old data and copy
40 array(const array &old_array)
41 {
42 delete []data;
43 data = new int[old_array.size];
44
45 memcpy(data, old_array.data,
46 size * sizeof(data[o]));
47 }
48 // operator =.
49 // Delete the old data and copy
50 array & operator = (
51 const array &old_array)
52 {
53 delete []data;
54 data = new int[old_array.size];
55
56 memcpy(data, old_array.data,
57 size * sizeof(data[0]));
58 return (*this);
59 }
60 public:
61 // Get a reference to an item in the array
62 int &operator [](const unsigned int item)
63 {
64 return data[item];
65 }
66 };
67
68 /**********************************************
69 * three_more_elements -- *
70 * Copy from_array to to_array and *
71 * put on three more elements. *
72 **********************************************/
73 void three_more_elements(
74 // Original array
75 array to_array,
76
77 // New array with modifications
78 const array &from_array
79 )
80 {
81 to_array = from_array;
82 to_array[10] = 1;
83 to_array[11] = 3;
84 to_array[11] = 5;
85 }
86 int main()
87 {
88 array an_array(30); // Simple test array
89
90 an_array[2] = 2; // Put in an element
91 // Put on a few more
92 three_more_elements(an_array, an_array);
93 return(0);
94 }


(Next Hint 8. Answer 75.)




















No comments: