Re: Validate a pointer

From: Måns Rullgård (mru_at_inprovide.com)
Date: 12/11/04


Date: Sat, 11 Dec 2004 22:34:02 +0100

Ara.T.Howard@noaa.gov writes:

> On Sat, 11 Dec 2004, [iso-8859-1] Måns Rullgård wrote:
>
>> Rich Teer <rich.teer@rite-group.com> writes:
>>
>>> As someone else suggested, if you want to know if a pointer is
>>> valid or not, arrange to trap the apprpriate signals, and handle
>>> them as you see fit.
>>
>> Don't do that. The signal may only be triggered after God knows what
>> damage has been done. Any (all) your data may have been trashed
>> before you hit an unmapped address.
>
> in some cases you might be able to simply fork and then dereference
> the pointer - the memory you trash will be the memory of the child
> unless you are doing something like mmap, etc. this is also quite
> expensive but, in some systems, not as much as it once was: perhaps
> equal to creating a thread. i guess it depends on how important and
> how often one would do this.

My point was that by the time you decide to dereference your possibly
invalid pointer, lots of data might have be trampled on. Likely areas
are your stack, in which case your program will anyway crash when the
current function returns.

There are no shortcuts to writing good code. Start with a good
design, implement it well, and you'll know which pointers are valid
without testing them.

-- 
Måns Rullgård
mru@inprovide.com


Relevant Pages

  • Re: Pointer and Its memory
    ... I dereference the pointer A using free. ... That is deallocating the memory it points at. ... Note that heap memory is an implementation detail, and not all systems even have a heap. ...
    (comp.lang.c)
  • Re: Confused about "void **"
    ... You cannot dereference a `void*' because ... memory of unknown size and significance. ... And what kind of a pointer points to a `void*'? ... of data object, ...
    (comp.lang.c)
  • Re: Malloc code
    ... to null when the associated memory is released. ... If you accidently try to dereference the pointer after it has ... On embedded systems with no mmu, ...
    (microsoft.public.vc.language)
  • Re: about std::string
    ... Because frequently it may be damaged but for a while the heap may appear to ... But with a damaged heap, ... Overwriting memory after the last valid byte obtained from ... Calling free,delete, deletemore than once on a non-NULL pointer. ...
    (microsoft.public.vc.stl)
  • Re: end of array
    ... You can make a pointer point to anything. ... I will probably get a segmentation fault or a memory fault. ... You don't have to attempt to dereference the pointer to invoke undefined behaviour. ... Merely calculating a pointer before or more than 1 past the end of an object invokes undefined behaviour even if you do nothing with it. ...
    (comp.lang.c)