I would like to recover 'gracefully' from this error instead of SEGFAULT. I can't check for NULL
since that would be 0. Do I explicitly check for address 0x1
?
Probably not the best idea.
The way to recover (technically, recovery is not plausible, you really need to prevent it instead) would be to assume that 0x1
is as bad as NULL
and not try to use it in that case, something like:
if ((p == 0) || (p == 0x1))
return;
// Otherwise use p.
However, I hesitate greatly in calling that graceful. The right thing to do is track down what's causing the pointer to be set to that invalid value and fix it. That's particularly apt since a piece of code dodgy enough to generate a pointer value of 1
would probably also be dodgy enough to generate 2
, or any other non-valid pointer.
Checking against 1
is akin to stopping headaches with a painkiller when someone's continuously smacking you in the head. You could take that tablet to ease the headache but surely it would be better to fix the root cause of the problem (i.e., stop the person smacking you in the head).