I had run into a strange problem, where I used to get an exception at the run-time with the message:
Unhandled exception at 0x0137d451 in I2cTlmTest.exe: 0xC0000005: Access violation reading location 0xcdcdcdd5.
I get this message during creation of object 'C'. I have debugged it but couldn't do much because the values of the (pointer) variables (and the this
pointer) are set to (0xcdcdcdcd) as soon as the debug hits the break point in B::getHelper
function of class B
. I looked around for the possible culprits, thinking that the variables might not be initialized or might be getting deleted before i reach the function. But in the A::getHelper
function all the variables are initialized and vanish when I enter the B::getHelper
function and are set to magic values.
After a bit of trial debugging I just moved the default-inline A::getHelper
to A.cpp. And to my wonder my application started running. I have solved my problem, but don't know why the inline function in A
is causing the trouble. Any help is highly appreciated. Sorry for the long question but didn't have any other choice.
I have tried to create a similar scenario with the following code snippet as mine :
-----classA.h---------
#include"classB.h"
class A
{
public:
// if the definition of `getHelper()` is moved to A.cpp runs fine. But, why ?
Helper* getHelper() const { return ptrB_->getHelper(); }
A()
{
ptrB_ = new B(this);
}
private:
B *ptrB_;
};
----classB.h-----------
class A;
class Helper
{
....
....
};
class B
{
public:
B(A *ptr):ptrA_(ptr){ helper_ = new Helper(); }
Helper* getHelper() const { return helper_; }
private:
A *ptrA_;
Helper *helper_;
};
-------classC.h--------
#include"classA.h"
class C
{
public:
C(A &ref): refA_(ref)
{
helper_ = refA_.getHelper();
}
private:
Helper *helper_;
A &refA_;
};
------main.cpp---------
#include"classC.h"
int main()
{
A *ptrA = new A();
C *ptrC = new C(*ptrA);
return 0;
}