Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Access violation reading location 0xcdcdcdcd error on calling a function

Please consider the below scenario:

I have a header file and its corresponding source file:

exmp.h (Header file)

exmp.cpp (Source file)

In the header file I have a function declaration bubSort(...) whose definition is present in

exmp.cpp

myClass::bubSort(...)
{

....
....

}

Where, myClass-> is a class defined in exmp.h

Now in order to use the function bubSort(...) in another file Sample.cpp, I have declared myClass inside Sample.h as shown below:

/*Sample.h*/
class myClass;

class sampleClass
{

  .....
  .....
  myClass *ptr;
};

Now using the above ptr, I'm trying to access bubSort(...) in Sample.cpp as shown below:

//Sample.cpp
#include "exmp.h"
sampleClass::func(...)
{
     ....
     ....
     ptr->bubSort(...);
}

The above scenario doesn't give any error during compilation, However while execution, when the control reaches ptr->bubSort(...);, I get an exception:

Access violation reading location 0xcdcdcdcd

Would anyone tell how I can avoid this?

Thanks in advance.

like image 563
Zax Avatar asked May 21 '26 17:05

Zax


1 Answers

ptr is a pointer to a myClass, but you don't seem to ever initialize it. In other words, ptr isn't pointing to anything. It's uninitialized -- pointing in to hyperspace.

When you try to use this uninitialized pointer,

ptr->bubSort(...);

You get Undefined Behavior. You're actually lucky that the application crashed, because anything else could have happened. It could have appeared to work.

To fix this problem directly, you need to initialize ptr. One way:

class sampleClass
{
public:
  sampleClass()
  :
    ptr (new myClass)
  {
  }
};

(For an explanation about the funky : syntax, look up "initialization list")

But this uses dynamic allocation, which is best avoided. One of the main reasons why dynamic allocation is best avoided is because you have to remember to delete anything you new, or you will leak memory:

class sampleClass
{
public:
  ~sampleClass()
  {
    delete ptr;
  }
};

Ask yourself if you really need a pointer here, or would doing without be ok?

class sampleClass
{
public:
  myClass mMyClass;
};

sampleClass::func(...)
{
  mMyClass.func();
}
like image 92
John Dibling Avatar answered May 24 '26 05:05

John Dibling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!