且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用函数时 C++ 访问冲突读取位置 0xcdcdcdcd 错误

更新时间:2022-06-19 06:07:51

ptr 是一个指向 myClass 的指针,但您似乎从未初始化它.换句话说, ptr 没有指向任何东西.它未初始化——指向超空间.

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.

要直接解决这个问题,需要初始化ptr.一种方式:

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")

但这使用动态分配,***避免.***避免动态分配的主要原因之一是你必须记住delete任何你new的东西,否则你会泄漏内存:

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