Archived

This topic is now archived and is closed to further replies.

Drastick

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

Recommended Posts

Drastick    132
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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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.

Share this post


Link to post
Share on other sites
quasar3d    814
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

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
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

Share this post


Link to post
Share on other sites
SabreMan    504
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.

Share this post


Link to post
Share on other sites