Thread: delete NULL;

  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    28

    delete NULL;

    I'm pretty sure that doing:

    Code:
    delete NULL;
    is perfectly safe, and is just a no-op. Yet everywhere I look, I keep seeing code like this:

    Code:
    int* ptr;
    ...
    if (ptr)
    {
       delete ptr;
    }
    WHY? The if guard isn't necessary, right? (Obviously it's good practice to assign a pointer to NULL after deleting it, but there's still no point in the if statement.) So why do people keep doing this? Is it still considered good practice (if so, why?), or is it simply the case that most C++ programmers think that deleting NULL is undefined?

    Just
    "C++ is like jamming a helicopter inside a Miata and expecting some sort of improvement."
    - Drew Olbrich

  2. #2
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,981
    >> ...or is it simply the case that most C++ programmers think that deleting NULL is undefined?
    Most likely.

    gg

  3. #3
    In fact,

    The C++ Standard ensures that NULL pointers will be safely deleted. This means that "delete NULL;" is perfectly legal and has a defined behavior. Some people will argue that some compilers are not quite "standard" though. Despite this issue it is useful to check for NULL just for debugging purposes in order to track double deletions of the same pointer (dangling pointer behavior).


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  4. #4
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    It seems that some old compilers may have had a problem.

  5. #5
    Registered User
    Join Date
    Aug 2003
    Posts
    470
    You should't write code like "if (ptr) delete ptr." You just end up complicating the code. Besides, even if some odd compiler had a problem, it's likely that you've missed a delete statement or two, and so you'd probably be better off redefining operator delete.

  6. #6
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Your pointers should always have a valid value. That is, they should either point to already allocated memory, or be NULL. As such, you should always set the pointer to one of these things when it is created, and after it is deleted. This avoids problems with delete. (Obviously, in a destructor, it is useless to set the value of a member pointer to NULL, but it is still a good habit.)
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  7. #7
    Registered User
    Join Date
    Jun 2004
    Posts
    124
    Is it nessesary to set a pointer equal to NULL after using the delete command? If you don't, then what does the pointer point to? Memory that is no longer allocated?

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    I simply always use a smart pointer of some sort, or a container. As of yet, I haven't written such performane-critical code that this would have been an unreasonable decision. And if I were writing such code, I'd try to keep allocations out of it anyway.

    Is it nessesary to set a pointer equal to NULL after using the delete command? If you don't, then what does the pointer point to? Memory that is no longer allocated?
    It is good practice, but not "necessary" per se. The pointer will most likely retain the value it last had (because the delete operator won't ever change it), but this is not guaranteed behaviour. Either way, (changing to something random or leaving it), dereferencing such a pointer is completely undefined behaviour.
    On Windows x86, the pointer still points somewhere on the heap, into memory that most likely can even be changed, and unless you have a debug allocation that fills unallocated space with a test pattern it won't even detect writes to it, so such bugs could lie dormant for a long time - until the execution path happens to allocate some more memory in that exact spot, which is then overwritten planlessly.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    Registered User
    Join Date
    Jun 2004
    Posts
    124
    Wow, CornedBee, that was way over my head hehe, i'm not a CS major Where do you learn about how the OS and the system deals with stack and heap memory and so on, i've never learned that in school but it seems to be nessesary knowledge if I want to really excel at C++.

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    I can't really answer that question. It's just stuff I've picked up along the way. Learning a bit of assembly is a good way of learning system internals. Writing your own bootstrap, too. Let me think... I've learned C++ from an absolutely excellent book, unfortunately I believe it's only available in German. "Programming Applications for Microsoft Windows" by Jeffrey Richter is a wonderful book, too. It talks about very advanced and system-near Windows programming, along the line teaching you a lot about how Windows does stuff like memory management, DLLs etc. On scanning the table of contents, this was obviously the book which taught me about Windows memory layout.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  11. #11
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    Code:
    if (one_object) delete one_object;
    one_object=NULL;
     
    if (multiple_objects) delete [] multiple_objects;
    multiple_objects=NULL;
     
    if (COMobject_interface_ptr) COMObject_interface_ptr->Release;
    COMObject_interface_ptr=NULL;
    These are perfectly fine for deleting objects both in COM and C++. They are safe delete's and safe releases. Every book I've ever read always tests the value of the pointer before deleting/releasing it. From my own personal experience I'd say it's a good habit to get into.

    And you are guaranteed that not only has your memory been de-allocated correctly, but all pointers to it destroyed, not just invalidated. They still point to that invalid area of memory and even though in C++ they are invalid....they still point to that memory or object.

    I don't recommend using these in your destructor code however. If your class specifically allocates memory or creates pointers to COM object interfaces delete and release in a specific function suited to the task. In this way you directly control object lifetime and you know the object is destroyed. I've run into some situations where COM completely failed inside of the destructor because it was called at some earlier point. Make sure you know when and where your object goes out of scope. Sometimes, like when using the STL libraries or other API's like DirectX/OpenGL and/or COM object lifetime is not always what you think it is. Also in COM if you fail to release the pointer then the reference count for the object never reaches 0 and thus is never destroyed. In essence...you have fragged COM for every other application in the system.
    Last edited by VirtualAce; 11-25-2004 at 07:14 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. New string functions
    By Elysia in forum C Programming
    Replies: 11
    Last Post: 03-28-2009, 05:03 AM
  2. Compiling 3rd party code problem me too
    By siavoshkc in forum C Programming
    Replies: 1
    Last Post: 09-12-2007, 05:55 AM
  3. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  4. Why am I getting these errors??
    By maxthecat in forum Windows Programming
    Replies: 3
    Last Post: 02-03-2006, 01:00 PM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM