Last time I wrote a piece about why initializing variables in C++ is very important. This time a short one about why destroying variables can be hell. Again for C++, since most other languages (Pascal excluded) do it for you.
Here’s the problem I’ve been facing lately: I work in C++ some of the time, and I try to delete every piece of memory I allocate. Sometimes, mostly by accident I do it twice. C++ doesn’t like this and it warns me with dbheap errors. Which is fine. By now I sorta understand what all of these errors mean.
So to prevent this I created a SafeDelete template. This is to take care of safely deleting any object and making sure it won’t happen twice. The template looks something like this:
template
void SafeDelete(PointerType*& pointer)
{
if (pointer != NULL)
{
delete pointer;
pointer = NULL;
}
}
I’m not shy on publishing this code, because I think it will help you. Especially when you are a beginning programmer. Deleting objects is now as simple as calling SafeDelete(object).
Just a quick one about why it’s important to initialize variables in code. Today I spent some time on finding a simple bug. The C++ debugger kept bugging me that I attempted to delete unallocated memory. Big nono
! Anyway I am sorta familiar with debugging and C++.
So the first thing I looked at was what was being deleted. For developers not using C++ in C you have to manually delete allocated memory or you’ll get the dreaded memory leaks
. What caught my eye was the memory address being deleted. It was 0xDCDCDCDC, which to my knowledge means the debugger never allocated it nor was it initialized.
This happened because I used a simple struct with three string objects (home made). In the destructor of the struct I did delete all the string objects. The function I use for this checks to see if the objects aren’t already NULL to prevent deleting non existing memory.
What I failed to do was initialize all variables to NULL in a constructor, which in most languages happens by default. Me working in more then one language forgot that in C++ no initialization is standard. So when debugging the debugger initializes to something it recognizes. But in a non-debug version you never now what is in the variable.
After fixing my constructor everything worked again. Thank GOD for that!