Question

I use operator() as a subscript operator this way:

double CVector::operator() (int i) const
{
 if (i >= 0 && i < this->size)
  return this->data[i];
 else
  return 0;
}

double& CVector::operator() (int i)
{
 return (this->data[i]);
}

It works when I get values, but I get an error when I try to write assign a value using

a(i) = 1;

UPD: Error text:

Unhandled exception at 0x651cf54a (msvcr100d.dll) in CG.exe: 0xC0000005: Access violation reading location 0xccccccc0.

Was it helpful?

Solution

Like I said in my comment, the problem is your flawed design. I make a 100% guarantee on one of two things:

  1. The value you are passing to the assignment function is out of valid range.
  2. The member data is pointing to invalid space in memory.

In either case, I would suggest adding:

#include <cassert>

and adding assert(i >= 0 && i < this->size) instead of the silent failures:

double CVector::operator() (int i) const
{
    assert(i >= 0 && i < this->size);
    return this->data[i];
}

double& CVector::operator() (int i)
{
    assert(i >= 0 && i < this->size);
    return (this->data[i]);
}

OTHER TIPS

That's because you haven't implemented error handling in double& CVector::operator() (int i) like you did for the other function which overloads ().

Change it to:

double& CVector::operator() (int i)
{
 if (i >= 0 && i < this->size)
 {
  return this->data[i];
 }
 else // Whatever manner you want to gracefully exit the program
 {
  std::cout<<"Out of bounds!"<<endl;
  exit(1);
 }
}

You should also consider changing the error handling mechanism in the other function from return 0; to something more meaningful.

Unhandled exception at 0x651cf54a (msvcr100d.dll) in CG.exe: 0xC0000005: Access violation reading location 0xccccccc0.

0xcc is the MSVC uninitialized memory byte value. In other words, your problem is most likely due to accessing an uninitialized pointer or a pointer that was derived from uninitialized memory.

The problem is that you do not check for out-of-range index in your double& version of operator().

You probably cannot guarantee that data[i] points to a valid memory address for a large enough i. You should either check for out-of-range index and throw some exception or resize your vector (by allocating more memory do data) to be able to hold more values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top