Re: assigning pointer to NULL



santosh wrote, On 31/01/08 08:20:
Ian Collins wrote:

Joachim Schmitz wrote:
user923005 wrote:
On Jan 30, 1:01 am, r...@xxxxxxxxxxxxxxxxxxxxxx (Richard Bos) wrote:
<snip>
P.S.
I almost always set freed pointers to null myself (the exception
being in C++ because it is pointless to set a deleted class member
pointer to null in a destructor.)
It helps with a very small class of problems (but does have one bad
side effect -- double frees are less likely to be detected)
But they won't harm (i.e. possibly crash the program) anymore either.

But the effect can be detrimental on a system (which includes most
desktop environments) where the allocator can detect duplicate frees.

For that reason, I never set a freed pointer to NULL.

Same here on the basis that, in C at least, the programmer *must* always
be aware of which pointers have valid or invalid values at all points
in his program. Anything short of this is going to lead to bugs. From
this P.O.V. setting dangling pointers to NULL is redundant.

In some situations setting pointers to NULL can be useful and used to indicate whether it is valid or not. For example, I have some code of this general form...

char *ptr = NULL;

/* do stuff */

if (cond1) {
ptr = malloc(something);
/* do stuff with ptr */
if (cond2) {
free(ptr);
ptr = NULL;
}
}
/* do stuff not using ptr */
if (cond3) {
/* do stuff using ptr */
free(ptr);
}


Note that the code deliberately has only one pointer to the malloc'd block.
--
Flash Gordon
.



Relevant Pages

  • Re: assigning pointer to NULL
    ... I almost always set freed pointers to null myself (the exception ... being in C++ because it is pointless to set a deleted class member ... desktop environments) where the allocator can detect duplicate frees. ...
    (comp.lang.c)
  • Re: How to make (ptr + len) > lim safe?
    ... Meaning I use ptr < lim where ptr and lim are both pointers ... However, if ptr and lim both point into or one past the end of the same array, and if ptr < lim, then lim-ptr has to be positive, and that is something the standard does say. ... Not directly, but by inference from what it says about the binary '-' operator and the '<' operator, when acting on pointers: ...
    (comp.lang.c)
  • Re: if I can get a pointer with objptr
    ... I think it was Bill Gates himself who decided that VB and VBA would ... not support pointers ... ... Every variant has a subtype ... ... dim ptr as long ...
    (microsoft.public.access.formscoding)
  • Re: regarding * and ++ operators
    ... The first area of confusion. ... declares ptr as a pointer to data of type char. ... It is comparatively rare for pointers to point to sinle objects. ...
    (comp.lang.c)
  • Re: free after realloc
    ... realloc() changes the size of the memory block pointed to by ptr to ... newly allocated memory will be uninitialized. ... If ptr is ... and had to change pointers ("area pointed ...
    (comp.os.linux.networking)