Showing posts with label memory. Show all posts
Showing posts with label memory. Show all posts

Tuesday, April 1, 2008

Detect Heap Corruption -- Using CrtCheckMemory()

To debug code that caused heap corruption,We normally do struggle against the computer in order to understand what causes the corruption and how.
In the search for memory validation APIs I have found _CrtCheckMemory() API which is being used by debug version of C run-time libraries. Using this API wrapped with an assert macro gives us the opportunity to check the heap every few lines of code without any overhead in release version: _ASSERTE( CrtCheckMemory());
it would be smart idea to use it even without any visible corruption, it saves time in the long run . This tip is based on information written on the MSDN.

Monday, March 24, 2008

Preventing object creation on stack

In C++, sometimes you don't want the user of your class to create the object of it on stack, because the stack resource is rare. Is there any way to do this?
Yes!!!
What you should do is to make your destructor private, rather than public or protected.
You can do like this:
class CTest {
private:
~CTest ();
}
Why only private, because if you make it protected, yes the object this class can't not be created on stack, but it's derived class can!

Then, if you want to create the object on stack, like
CTest test;

The compiler is gona complain, the error message is most probably like 'CTest::~CTest' : cannot access private member declared in class CTest'.

That's because the compiler will actually check if it can delete the object if it's created on stack, because it's compiler's business to take care of this. If you do like:
CTest* test
or
CTest* test = new CTest
It's gona be fine, because the only thing you put on the stack is just the pointer, compiler don't even have to call the destructor of the pointer.
Then, how do you delete the object whose destructor is private?? Just use delete operator is not going to work, because delete operator is not a part of the CTest class. So you have to provide a function which will delete the object itself.
It's like:
void CTest::Release()
{
delete this;
}
Since "delete this" is not a "good manner"(it works, but it's not recommended), you have to pay more attention when you use this. You have to make sure that the object is not created by "new[]". You have to make sure Release is the last function you call on this object, etc.