Way to test if a pointer has been assigned "new"

Started by
4 comments, last by Drastick 20 years, 9 months ago
I am writing a function that that is passed a pointer that has been assigned as new (allocated memory), I want to add some error checking to make sure nothing gets pass which has not been allocated, is there a way to for test this? Thanks
Advertisement
new will either throw an exception or return 0 if there is an error during allocation.


Qui fut tout, et qui ne fut rien
Invader''s Realm
If you are on Windows there is a function called:

int _CrtIsValidHeapPointer( const void *userData );

(from the MSDN) which is debug only which will do what you need. MSDN says you need to #include <crtdbg.h> to get it.
quote:Original post by Invader X
new will either throw an exception or return 0 if there is an error during allocation.


Qui fut tout, et qui ne fut rien
Invader''s Realm


Does new throw an exception? what exception? I thought it just returned zero if something went wrong (out of memory).



My Site
quote:Original post by Drastick
I am writing a function that that is passed a pointer that has been assigned as new (allocated memory), I want to add some error checking to make sure nothing gets pass which has not been allocated, is there a way to for test this? Thanks


WHen declaring the pointer or in the constructor of the class the pointer resides in, set the pointer to NULL or 0 (same thing);

Then allocate the pointer.

if(!Pointer)return; //pointer is zero

or

if(Pointer == NULL) return; //pointer is zero
quote:Original post by quasar3d
Does new throw an exception? what exception?

std::bad_alloc.
quote:
I thought it just returned zero if something went wrong (out of memory).

It does under certain compilers, but it''s non-standard.

This topic is closed to new replies.

Advertisement