Re: Detecting freed memory



>int *p;
>
>p = malloc(1);
>
>free(p);
p; /* possible smegmentation fault here */
>
>/* */
>
>
>In the above code, how do I detect that variable p points to nothing?

You can't even TRY: doing anything with the value of p invokes the
wrath of undefined behavior. You might try setting p to NULL
immediately after the free() call, but *DO NOT* assume that the
fact that it's not null means it points somewhere valid unless you
are sure you've coded it that way. Why? Code like:

destructor(p); /* free p and its associated buffers */

cannot set p to NULL in the calling function, assuming destructor()
is an actual function. More often, a function cannot set all of
the copies of the pointer it's freeing to NULL because it doesn't
now where the copies are.


>In other words, how do I detect a freed memory pointer, as opposed to a
>pointer that points to allocated memory?

Keep track of it yourself.

Gordon L. Burditt
.



Relevant Pages

  • Re: free()
    ... freeing a goat will have to deal with this. ... going to give it a new value, so no point nulling it. ... rather than nulling the pointer because you're freeing it ...
    (comp.lang.c)
  • Re: double free
    ... >Does anyone know of a good website that actually describes and ... implementation dependent. ... Obviously the proper way to handle freeing a pointer more than once is ...
    (comp.lang.c)
  • Re: free()
    ... thing, but also because it's actively obfuscating serious problems, ... If a pointer is null, you can free it as often as you like. ... freeing an invalid pointer has undefined and indeterminate results. ...
    (comp.lang.c)
  • Re: Why it is not good code for constructor
    ... How can C's destructor free the memory? ... responsible for freeing it, but C::~C will not be called, and a function-try ... handler cannot access the pointer, while a catch handler in local scope will ... now if new intcompletes ok, but the constructor for A throws, the ...
    (microsoft.public.vc.language)
  • Re: double free
    ... > demonstrates WHY freeing a pointer more than once is a problem. ... In all others, there is a block twice in the free list, ... address and when you write into one you corrupt the ...
    (comp.lang.c)