How to check if an object pointer is valid

On this Monday, I was about to write codes to check validity of a pointer. It turned out that I didn’t need to. However, I wonder how to do it.

There is no such things in Unix functions and Cocoa framework. Whenever I wrote codes, I didn’t need such check because I always depends on certain function’s return state whether it was successful to retrieve data or not. I searched on Google and I found hilarious statement from StackOverflow or somewhere else. “Don’t need to check validity of pointers. Educate your programmers!”

It is true. In most cases, functions, which returns some memory address by allocating those and populate data in that area, returns error codes to say what happened. Programmers are encouraged to check those error codes, or simply NULL to a pointer variable which is expected to point to newly allocated memory area. Then you don’t need to check the validity of the pointers.

Memory debugging libraries like Valgrind supports validation of address. However, they are only for debugging mode. You are not supposed to use those in release build of your program.

However, what if you really need it?

Theoretically, it is just guessing. If very unfortunate address is returned and it points to valid area of memory somehow, it can’t be assured that the address is contextually valid.

At Cocoa with Love, he even mentioned that. However, as a helper it would be better to have validity checker for a pointer though it is not perfect.

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: