Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
893 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...