Rogue array pointers


Home

About the Author

General Programming

Pascal

Delphi

C&C++

Visual Basic

SQL

JAVA Script

Links

 

Assert vs Verify ] Constructors and Destructors ] Falling through switch statements ] Memory Leaks ] Null Terminator ] [ Rogue array pointers ]

C++ doesn't support boundary checking on its arrays, and this leads to some of the worst bugs that your program could ever have.

Here's an example:

char Name[5]; //indexes are 0-4 (5 units in this array)

for (int i = 0; i = 5; i++)

{

Name[i] = "b"

}

What happens here is that the loop runs six time (not five) and Name[5] has the letter b written to it. What is Name[5]? It's not part of your array, but rather another address in your memory that something else was probably using. The reason that C++ allows this while other language catch this for you (i.e. Visual Basic) is because the additional error trapping that would be necessary would make C++ much slower. This additional overhead was deemed unacceptable and was left as is (the way C handled it). You could write dianostic member functions inside of your classes to help avoid this, but bear in mind the overhead that it may involve. The best advice here is to watch loops and functions that act on your arrays, and perhaps even use constants in your array parameters instead of numbers that are easy to forget:

const MAXARRAY = 20;

char Name[MAXARRAY ]; //indexes are 0-4 (5 units in this array)

for (int i = 0; i < MAXARRAY ; i++)

{

Name[i] = "b"

}

 If this for loop was further down in your code, then keeping track of a few constants is much easier then trying to remember a bunch of meaningless numbers.

Link of the week 
http://www.cpp-
programming.
com/
Newsgroups
comp.lang.c
comp.lang.c++
comp.programming

This page is best viewed in 800x600x256. This page was last edited Saturday, July 15, 2000

1