Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

visual c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...