Delete memory error
-
24-09-2019 - |
Question
I have the following scenario,
class foo
{
...
private:
char *_test;
};
void foo::setTest()
{
if( 0 != _test ) delete [] _test;
}
The function setTest
throws an error when called, as it trying to delete _test
when it has not yet been assigned. This is happening because _test
is not set to 0X0.
Can anyone help me to understand this?
Solution
You should initialize _test with NULL
in the constructor.
Like:
foo:foo {
_test = NULL;
}
If you don't _test will have garbage value.
Also as pointed by Chris, The value passed as argument to delete
or (delete[]
) must be either a pointer to a memory block previously allocated with new
, or a null pointer (in the case of a null pointer, delete produces no effect), effectively making your NULL check redundant.
OTHER TIPS
Well, if _test
has not been assigned any value, then it has undefined value. You can't use that value for anything, if you want sane behaviour. Variables need to be assigned before being used.
Incidentally, delete
and delete[]
is safe to call on null pointers, so the == 0
check is redundant.
There are two possibilities:
If you never initialize foo::_test
, then that variable will likely contain random data when your class is constructed. C++ does not initialize your pointers to null (unlike Java, C#, or most other higher-level languages). You should always (ALWAYS!) initialize your pointers to NULL
or a valid value. Change to char *_test = NULL;
or otherwise initialize _test
in your constructor.
Alternately, it's possible that _test
is being deleted in a different place not shown in your sample, but isn't being set to NULL
. Whenever you delete a class member, you should set it to NULL
afterwards in order to prevent this sort of double-free problem.