I use new to allocate a buffer, as follows:
BYTE *p;
p = new BYTE[20];
...
delete p;
After p is deleted, if I do NOT assign NULL to p, is there a way to determine whether it has already been freed?
Thanks
Printable View
I use new to allocate a buffer, as follows:
BYTE *p;
p = new BYTE[20];
...
delete p;
After p is deleted, if I do NOT assign NULL to p, is there a way to determine whether it has already been freed?
Thanks
Yes, but not in your code. It is how DEBUG_NEW works.
In your code you have to assign NULL to p after deleting it:Code:delete p;
p = NULL;
1. With delete instruction , write p = NULL; Then u can easily check.
2. Increment a flag variable with new and Decrement the same with delete.
When it is 0 , assign the size ...
as new is allocating memory for an array, then the array version of delete should be usedCode:BYTE *p;
p = new BYTE[20];
...
delete p;
Code:delete [] p;
Instead of having new/delete in your code - which can be prone to errors, consider using RAII construct or unique_pointer/shared_pointer.
While unique_ptr will work since it has support for array-delete. it's worth mentioning that shared_ptr does not and should thus not be used for arrays. There was talks about adding this to C++14 but I haven't managed to keep entirely up to date on that. It's on my list of things to do in 2015. :p
For databuffers however, it's typically easier to use vector instead of unique_ptr.
unique_ptr with array-delete does have it's uses when you're getting the raw array pointer returned from some "older" bit of code where you don't have so much control over or which for various reasons can't (aren't allowed to) be changed to use a vector. I would call it a last resort when for whatever reason vector is out. (I do mean the "with array-delete" specific here, there is definately a use for unique_ptr on single objects).