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.