more vector debugging problems

Started by
3 comments, last by Antheus 16 years, 2 months ago
Ive got a function for checking if a system exists. For some reason on the 2nd part i'm getting assertion errors. If I press ignor once I get a diffrent error and a 2nd time v32008 says it detected a fatal error...

bool check_system(int sys)
{
	if(prt::system_list.size()-1 < sys)
	{
		if(error_log)cgm::log<<"Tried to access non existant system: " << sys << "\n";
		return false;
	}
	if(prt::system_list[sys]==NULL)//vector subscript out of range//Standard c++ libaries out of range
	{
		if(error_log)cgm::log<<"Tried to access non existant system: " << sys << "\n";
		return false;
	}
	else return true;
}


Advertisement
if(prt::system_list.size()-1 < sys)

I'm assuming you want sys to be an index less than the size of the system. If that's so, then your conditional should be sys < prt::system_list.size( ). Otherwise, you'll return false on a valid index (excluding the last element in the list due to your current conditional). In the opposite case you will not return false from an invalid index and then proceed to to access the array in the next if statement.
Actually my way turned out to be right (it returns false if the size is less than the id).

the problem was that size() returns an unsigned type so when the size was 0 taking 1 away caused it to wrap around making the sizer appear bigger than the id so Ive added a type cast to int before taking 1 away now.
Consider turning your compiler's warning level up. With MSVC at warning level 4, the comparison should have generated a C4018 warning you about a signed/unsigned comparison.

Also, you should prefer comparisons that don't perform any arithmetic on either side of the operator, for reasons that you've just found now. For example, this expression could have been written prt::system_list.size() >= sys

Why not:
bool check_system(unsigned int sys){  return sys < prt::system_list.size();}

This topic is closed to new replies.

Advertisement