avoiding errors caused by overshooting array bounds

I just spent a lot of time debugging a problem that turned out to be an easy fix. In an array sort routine, in my loop, I was overshooting the array bound, apparently SOMETIMES causing my array to be contaminated with a garbage value. It was driving me nuts because sometimes it worked perfectly and sometimes it didnt. The code is below and the fix was changing "n-1" to "n-2".

My question is: Is this sort of thing something I'm just going to have to get used to in C (I am new to C ... VB would have given me an index out of bounds error and I would have had it fixed in seconds), or is my approach to the problem somehow problematic and prone to intermittent errors that are hard to find?

Thanks for any advice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
	int SortDoubleArrayAbsolute(int n, double * inArray)
	{
		try{
		double temp;
		bool bDone = false;
		while(!bDone)
		{
			bDone = true;
			for(int i = 0; i<= n-2; i++)
			{
				if (fabs(*(inArray+i)) > fabs(*(inArray+i+1))) 
				{
					temp = *(inArray+i);
					*(inArray+i) = *(inArray+i+1);
					*(inArray+i+1) = temp;
					bDone = false;
				}
			}
		}
		return 0;
		}
		catch(const char amessage[])
		{
			return 5;
		}
	}
Last edited on
Maybe you should have used < instead of <= in the for.
If you use std::vector and access elements with at() you'd get an exception when you go out of boundaries.
If you use raw pointers / arrays you have to manage memory yourself and be sure that everything you do is correct
Thanks Bazzy,

I was hoping there would be something that marked the end (null or whatever)... guess not. Thanks again!
As Bazzy says your <= control provides the opportunity of exceeding array bounds and should use <.
My understanding is that a string in 'C' is [always] an array which ends with a mandatory '/0' or NUL character.The <cstring> header provides the many functions for manipulating C strings. For example strlen(s) will return the number of characters in string 's' not counting its terminating NUL character.
C strings may not be NUL-terminated, they usually are but the programmer must be sure of this before using a function that expects a \0-terminated char array
Topic archived. No new replies allowed.