dereferencing null

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Mar 7 07:55:35 PST 2012


On Wed, Mar 07, 2012 at 09:22:27AM -0500, Chad J wrote:
> On 03/07/2012 07:57 AM, Steven Schveighoffer wrote:
[...]
> >However, there are several causes of seg faults:
> >
> >1. You forgot to initialize a variable.
> >2. Your memory has been corrupted, and some corrupted pointer now
> >points into no-mem land.
> >3. You are accessing memory that has been deallocated.
> >
> >Only 1 is benign. 2 and 3 are fatal. Since you cannot know which of
> >these three happened, the only valid choice is to terminate.
> >
> >I think the correct option is to print a stack trace, and abort the
> >program.
> >
> 
> Alright, I think I see where the misunderstanding is coming from.
> 
> I have only ever encountered (1).  And I've encountered it a lot.
> 
> I didn't even consider (2) and (3) as possibilities.  Those are far
> from my mind.
> 
> I still have a nagging doubt though: since the dereference in
> question is null, then there is no way for that particular
> dereference to corrupt other memory.  The only way this happens in
> (2) and (3) is that related code tries to write to invalid memory.
> But if we have other measures in place to prevent that (bounds
> checking, other hardware signals, etc), then how is it still
> possible to corrupt memory?
[...]

It's not that the null pointer itself corrupts memory. It's that the
null pointer is a sign that something may have corrupted memory *before*
you got to that point.

The point is, it's impossible to tell whether the null pointer was
merely the result of forgetting to initialize something, or it's a
symptom of a far more sinister problem. The source of the problem could
potentially be very far away, in unrelated code, and only when you tried
to access the pointer, you discover that something is wrong.

At that point, it may very well be the case that the null pointer isn't
just a benign uninitialized pointer, but the result of a memory
corruption, perhaps an exploit in the process of taking over your
application, or some internal consistency error that is in the process
of destroying user data. Trying to continue is a bad idea, since you'd
be letting the exploit take over, or allowing user data to get even more
corrupted than it already is.


T

-- 
Be in denial for long enough, and one day you'll deny yourself of things you wish you hadn't.


More information about the Digitalmars-d mailing list