Re: History of - if(p) delete p; - ... ?



Martin T. wrote:
Hi all.

As things are the following works just fine under Visual Studio:

int* p=NULL;
free(p); // If memblock is NULL, the pointer is ignored and free
immediately returns.
delete p; // The default behavior for a null value of _Ptr is to do
nothing. delete[] p; // The default behavior for a null value of
_Ptr is to do nothing.
p = NULL;


However, our code base uses the following construct basically all
the time: int* p = ...
if(p)
free(p); // or delete, or delete[]
p = NULL;

I think the code was initially created on Visual Studio 4 and then
got ported over the years to 5/6/now 2005 ...
I'm trying to figure out why we always used this construct even
though it's not necessary.
Was it *ever* necessary? Pre VC6, pre VC5, ... ?? Has the free
function in C always been specified as noop in case of NULL ?


For pre-standard C it was actually needed on some compilers. Since
around 1989 it shouldn't be. :-)

On the other hand, it doesn't hurt much. If you check the code
generated by recent MSVCs, you will see that

if (p)
delete p;

and

delete p;

generates identical machine code. If you don't check for a null
pointer, the compiler will have to. If you check, the compiler will
not!



Bo Persson


.



Relevant Pages

  • Re: forwards declarations!
    ... h, long m, int w, int l); ... compiler obviously doesn't. ... LRESULT callerFunction(HWND, long, WPARAM, LPARAM), HWND ... Not quite the same as straight forwards function pointer usage. ...
    (microsoft.public.vc.language)
  • Re: Common Problems that Compilers Dont Catch
    ... where the compiler offered no help. ... Become more familiar with pointer variables and you won't be making such ... int i = p; ... Any pointer type may be converted to an integer type. ...
    (comp.lang.c)
  • Re: Inconsistent Program Results
    ... Why do you lie to the compiler? ... you define later takes an argument, a pointer to pointer to ... Under both Windows and Linux mainalways returns an int (and ... not know about the return type of malloc(). ...
    (comp.lang.c)
  • Re: Newbie question
    ... mainis a function that returns an int. ... can correct that by passing a pointer to the structure to the func- ... tion and operate on the structure belonging to the caller via this ... Some of the problems the compiler can tell you about if you invoke it ...
    (comp.lang.c)
  • Re: Confused with malloc
    ... malloc without prototyppe gets ... interpreted as int malland this gets you code like: ... Not every compiler uses one and the same location with exactly the ... same number of bits for int and pointer to something. ...
    (comp.lang.c)

Quantcast