Your interviewer was a jerk.
Unfortunately, there is no standard
C++ way to protect against an access violation.
Some compilers (such as MSVC) have special constructs (__try
blocks) that will allow you to catch things like access violations. In the *nix world, you will probably wind up playing with signals (or, preferably, POSIX’s sigaction
Here is a blog I found that goes into some details (and frustration):
(NullPointerException in C++
If you want to validate that a pointer addresses memory that belongs to you, again, that can be done, but not with C++: you need OS-specific libraries for that.
C++ cannot help you (much), but it can be done with OS-specific code. Again, refer to the blog link for what C++ is capable of doing for you.
Oh, I might as well tackle the question you were given. The correct answer is:
Don’t do that!
Always maintain ownership of your pointers. (And, unless requirements forbid, use C++ facilities to avoid using pointers at all, like std::unique_ptr
and, yes, references
Unless your pointer is known to be initialized from:
• an extant, in-scope object
• a memory manager (ie, using new
or even OS-specific utilities like GlobalAlloc()
... then you should not dereference it.
Part of the way you prevent invalid accesses is to carefully manage your pointer’s scope. Initialize it when created; destroy it when you are done with it. In other words, make it impossible to access something that is bad.
Hope this helps.