I have a zap() function written to deallocate a 1-d array as follows.
void zap(double *(&data))
{
if (data != NULL)
{
delete [] data;
data = NULL;
}
return;
}
I was under the impression that if data != NULL would not try to deallocate memory that had never been allocated, but I think I am mistaken. I am having the following implementation problem.
void fun()
{
int condition = 0;
double *xvec;
double *yvec;
allocate_memory_using_new(yvec); //a function that allocates memory
if (condition == 1) allocate_memory_using_new(xvec);
//some code
//deallocate memory:
zap (yvec);
zap (xvec); //doesn't work
return;
}
The output is the following:
Unhandled exception at 0x6b9e57aa (msvcr100d.dll) in IRASC.exe: 0xC0000005: Access
violation reading location 0xccccccc0.
So I realize it is not a desirable thing to try to call zap when it is obvious that the pointer was never actually used. I am just wondering if there is a way to check the address of the pointer at some point in the zap() function to avoid the exception. Thanks in advance for your help and insight!
Pointers do not get magically initialized to 0, only when they are global or static. You need to do so:
If you do not, they contain random junk that was left on the stack where they are created. And this junk is most of the time not
NULL.Also, you do not need to check against
NULL, asdeleteis a no-op in that case:Further, if you’re working with Visual Studio 2010, I recommend to use
nullptrinstead ofNULL.