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?
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.