Please consider the below scenario:
I have a header file and its corresponding source file:
exmp.h (Header file)
exmp.cpp (
0xcdcdcdcd
means uninitialized data.
This means you're trying to access an uninitialized pointer somewhere.
Read more about it here:
Troubleshooting Common Problems with Applications: Debugging in the Real World
Win32 Debug CRT Heap Internals
I can see stars.
Does this work instead?
class sampleClass
{
.....
.....
myClass ptr;
};
Do not use pointers unless you know what you are doing.
You didn't initialize pointer, so you're calling empty memory. It is 0xcdcdcdcd and not some random stuff because of visual debugger.
ptr = new myClass();
This will do. But you don't have to use pointer in this case at all.
in order to solve it (one possible way), you must make 'ptr' actually to point to a adress where a myClass objects exists. In order to exist, you have to create it, e.g.
class sampleClass
{
public:
sampleClass()
{
ptr = new myClass();
}
private:
myClass* ptr;
};
you might still consider using C++11's unique_ptr or shared_ptr instead of a raw pointer, though.
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();
}