Problems with Array Boundaries


I want to leave you with a final cautionary note before we end our discussion of arrays. The misuse of arrays is an excellent way to crash your program. Here's an example of what I mean:

 int thisArray[10]; int i = 0; while (i<50) {     thisArray[i] = i;     i++; } 


You've probably spotted the problem with this code fragment. The array only holds 10 integers. However, the loop tries to store 50 integers into the array.

What happens when you execute code like this?

I think the result of code like this is best summed up with the phrase "crash, burn, and die."

To be more specific, the loop actually executes. It stores 50 integer values starting at the beginning of thisArray. Of course, the array only has enough memory for 10 integers. Even so, the program keeps going right past the end of thisArray. It happily writes integers as it frolics its way through your computer's memory. Whatever else might be at those 40 locations beyond the end of thisArray gets completely overwritten. It is not uncommon for the contents of the overwritten locations to contain information that is critical to the operation of your program. As a result, your program crashes, losing whatever data was not saved. Users don't take kindly to that.

When your program accesses memory before or after the array, programmers say that it is "going beyond the array boundaries." If you try to use negative values as array index numbers, you are outside the array's boundaries.

C++ does not prevent you from going outside an array's boundaries. Depending on which compiler you use, your compiler may or may not be able to figure out the problem and give you an error. Except for the most simple and obvious cases, most compilers won't catch the problem.

Tip

Array boundary problems are very common in programs, so you should double-check for them in every loop that uses an array.


How do you detect this problem? Simple: your program crashes. Use your debugger to check whether your program crashes when it's in a loop that uses an array. It if does, the first thing you should examine is whether the index numbers are outside the boundaries of the array.



Creating Games in C++(c) A Step-by-Step Guide
Creating Games in C++: A Step-by-Step Guide
ISBN: 0735714347
EAN: 2147483647
Year: N/A
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net