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...@hoekstra-uitgeverij.nl (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 s 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
|