调用函数时 C++ 访问冲突读取位置 0xcdcdcdcd 错误
请考虑以下场景:
我有一个头文件和它对应的源文件:
I have a header file and its corresponding source file:
exmp.h(头文件)
exmp.cpp(源文件)
在头文件中我有一个函数声明 bubSort(...)
其定义存在于
In the header file I have a function declaration bubSort(...)
whose definition is present in
exmp.cpp
myClass::bubSort(...)
{
....
....
}
其中,myClass->
是exmp.h
现在为了在另一个文件Sample.cpp中使用bubSort(...)
函数,我在myClass
中声明了myClass
strong>Sample.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;
};
现在使用上面的ptr
,我试图访问Sample.cpp中的bubSort(...)
,如下所示:
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(...);
}
上述情况在编译过程中没有给出任何错误,但是在执行时,当控件到达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:
访问违规读取位置0xcdcdcdcd
Access violation reading location 0xcdcdcdcd
谁能告诉我如何避免这种情况?
Would anyone tell how I can avoid this?
提前致谢.
推荐答案
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();
}
相关文章