Thread: checking memory/pointer if it's valid before deleting

  1. #1
    Registered User
    Join Date
    Jul 2004
    Posts
    222

    checking memory/pointer if it's valid before deleting

    I'm trying to find out a proper practice of checking if the pointer/array is valid before calling the delete operator. I know I can check if the pointer is a NULL pointer before deciding whether I should call the delete operator, but that doesn't take care of the case of a dangling pointer. In other words, how do I check whether I have proper access to the memory that the pointer is pointing to before calling the delete operator?

    Thanks in advance for suggestions.

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    You can't check if the pointer is dangling. The best practice is to do:
    Code:
    delete my_pointer;
    my_pointer = NULL;
    It is OK to delete a NULL pointer, so you don't need to check if it's NULL before calling delete.

  3. #3
    Registered User
    Join Date
    Jul 2004
    Posts
    222
    What happens if I would allocate my_pointer again right after delete? Would it get assigned to an address that has enough memory in the heap?

  4. #4
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    Yes.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Profiler Valgrind
    By afflictedd2 in forum C++ Programming
    Replies: 4
    Last Post: 07-18-2008, 09:38 AM
  2. Forced moves trouble!!
    By Zishaan in forum Game Programming
    Replies: 0
    Last Post: 03-27-2007, 06:57 PM
  3. recursion error
    By cchallenged in forum C Programming
    Replies: 2
    Last Post: 12-18-2006, 09:15 AM
  4. Problems about gcc installation
    By kevin_cat in forum Linux Programming
    Replies: 4
    Last Post: 08-09-2005, 09:05 AM
  5. checking for valid numeric field..
    By ronkane in forum C++ Programming
    Replies: 3
    Last Post: 01-22-2002, 09:04 PM