Friday, August 21, 2009

delete pointer

is there anything wrong with this code?

T *p = 0;
delete p;


environment: C++
click here for answer


deleting null pointer invokes no operation in c++. in short it is safe to delete null pointer.

as per the standards:
5.3.5 (6): If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted. In the case of an array, the elements will be destroyed in order of decreasing address (that is, in reverse order of the completion of their constructor; see 12.6.2).


a smarter answer would be to ask if the delete is overloaded in T class. if it is overloaded, then the function had to be seen to figure out if anything can go wrong.


it would be a wise move if you nullify a pointer after deleting it. so that if that pointer is again attempted to delete later elsewhere in the program, it wont crash. deleting a pointer which was already deleted might lead to program crash.

delete p;
p=NULL;

but there are many debates going on around this nullifying a deleted pointer, should the developer do this for every delete, if it is important why dint c++ standard already hadnt done this.. and how often would such occurrence like deleting a deleted pointer might occur.. etc. its upto you to figure out opt way to code your stuff.


3 comments:

  1. A few years back I wld have said that you must not delete a zero pointer; but actually u can, without error.
    The only thing wrong seems to be that the code is not doing anything :).

    ReplyDelete
  2. u Didn't initialized it with new
    so u cant use delete

    if u say

    int *r;

    r = new int[5];

    then u can say
    delete r;

    and u cant do in some cases
    like
    T *r = 0;
    that must be
    T *r;
    r= &d;

    m a game programmer if u need any help u can
    contact me on tarun533@yahoo.co.in
    or
    join my community on orkut
    http://www.orkut.co.in/Main#Community.aspx?cmm=50600020

    ReplyDelete
  3. Tarun,
    your logic is correct, but with one exception.. delete can be called on null pointer. it does not take any action hence it is safe. plz click "click here for answer" to know more.

    ReplyDelete