read access violation. this was 0xCDCDCDCD

1.5k Views Asked by At

I'm confused as to what I'm doing wrong? While debugging, this shows 0xcdcdcdcd {theDouble=??? }so i know my variable isnt getting stored in my mutator. How would i go about fixing this issue? Am I supposed initialize this somewhere? I am using visual studio by the way. Thank you for the help.

int main()
{
    int i = 0;
    const int MAX = 4;
    CLASS **object = new CLASS*[MAX];
    string name = "todd";
    string aString = "words";
    double aDouble = 10.0;
    object[i]->setDouble(aDouble);
    return 0;
}

//.cpp
CLASS::Class()
{
    theDouble = new double;
    *theDouble = NULL;
}
CLASS::Class(double aDouble)
{
    *theDouble = aDouble;
}
void CLASS::setDouble(double p)
{
    *theDouble = p; 
double Class::getDouble()
{return (*theDouble);}

//.h
class CLASS
{
 protected:
    double *theDouble;
 public:
    Insurance();
    Insurance(double premium);
    //~Insurance();
    void setDouble(double p);
    double getDouble();
    string toString();
   };`
1

There are 1 best solutions below

0
On

You use CLASS, Class and Insurance in mix where you should use one name so your posted code can not compile. I replace those with IronMan.

What you see as 0xCDCDCDCD is not this pointer value but value of the pointer member theDouble. The issue comes from in constructor:

IronMan::IronMan(double aDouble)
{
    *theDouble = aDouble;
}

That constructor dereferences uninitialised member variable theDouble and since debuggers tend to fill uninitialized memory with some bytes like 0xCD you will have that as value of the pointer. Therefore you get a crash for accessing memory at such address.

One way out of it is to allocate memory for theDouble

IronMan::IronMan(double aDouble)
{
    theDouble = new double(aDouble);   
}

Better would be likely to avoid using pointers there at all but just have direct double data member:

protected:
    double theDouble;