Thread: using the C++ delete operator

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    31

    using the C++ delete operator

    Hello,

    I have a module as shown below:

    Code:
    void FreeMemory(void *mem)
    {
        delete mem;
    }
    This memory had been previously allocated using the new operator.

    When I was running a unit testing tool for this function, the program crashes on the delete operator. It actually passes a pointer which was not allocated previously using new operator.

    Code:
    char *p;
    
    FreeMemory(p);
    I read that the new operator, gives an exception if it fails to allocate memory.
    However, the delete operator does not raise an exception and simply crashes.

    Now, how do I get around this problem and make sure the test case passes successfully ?

    Any suggestions?

    Thanks

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    The above code doesn't use the new operator (duh, I know, but you never know). Re-check that you have allocated memory (maybe the new threw an exception but you didn't exit the program?

    Maybe you call it twice? Try this
    Code:
    void FreeMemory(void *mem)
    {
         if (mem == NULL) return;
         delete mem;
         mem = NULL;
    }
    this ensures you cannot call it twice.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by C_ntua View Post
    The above code doesn't use the new operator (duh, I know, but you never know). Re-check that you have allocated memory (maybe the new threw an exception but you didn't exit the program?

    Maybe you call it twice? Try this
    Code:
    void FreeMemory(void *mem)
    {
         if (mem == NULL) return;
         delete mem;
         mem = NULL;
    }
    this ensures you cannot call it twice.
    I didn't read the post, but delete has no effect on NULL. That is, it must check for NULL itself and do nothing if it is NULL. So just as well:
    Code:
    delete mem;
    mem = NULL;

  4. #4
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Just don't use uninitialized variables. The C++ language doesn't protect you in any way if you do.

    The compiler can even normally tell if you are using uninitialized variables if you enable warnings:

    Code:
    void FreeMemory(void *mem)
    {
        delete mem;
    }
    
    int main()
    {
        char *p;
        FreeMemory(p);
    }
    Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
    Copyright 1988-2008 Comeau Computing. All rights reserved.
    MODE:strict errors C++ C++0x_extensions

    "ComeauTest.c", line 9: warning: variable "p" is used before its value is set
    FreeMemory(p);
    Another issue could be that it might be incorrect to pass a void* to delete.

    As to assigning NULL to mem, this is pointless since the copy of the pointer goes out of scope anyway. Checking for NULL before deleting is also pointless, and generally there is no way to check if the pointer, should it be non-NULL, points to something deletable. Generally one would use containers, smart pointers etc, so that delete wouldn't be used anywhere in the code in the first place.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  5. #5
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Actually I am surprised it compiled. Most of the time if you are going to delete a void *, you have to cast it to the type that you are actually deleting. IOW:
    Code:
    MyClass *ptr = new MyClass;
    FreeMemory((void*)ptr);
    
    
    ...
    void FreeMemory(void *pMem)
    {
          delete pMem; // this is no good
          delete (MyClass *)pMem; // this should work
    }
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Agreed. This FreeMemory function is an abomination. Remove this function and just call delete at the appropriate place. Or alternatively, make it templated on the type of item being deleted.
    No C++ program should ever have a function that performs a delete without knowing the type of the thing it is deleting.

    In addition to that, fix the test case. You're probably trying to delete the address of some local variable or something like that.

    Oh and C_ntua, consider yourself shot for those two redundancies you suggested.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  7. #7
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    Quote Originally Posted by iMalc View Post
    Oh and C_ntua, consider yourself shot for those two redundancies you suggested.
    Lol. I am fairly ashamed to admit I missed that mem was a parameter. And even a non-reference one...

  8. #8
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Another problem with managing things yourself is that there isn't really a practical way to differentiate between arrays (which require a call to delete []) and single objects.

    Conclusion: Use RAII. Always.
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by EVOEx View Post
    Lol. I am fairly ashamed to admit I missed that mem was a parameter. And even a non-reference one...
    Yeah I hope he realises I was being partially humourous.
    Probably anyone with more than a few hundred posts on these forums should at least know by now that there's no need to check for NULL first. I'm sure C_ntua is normally is a bit more clued up than that. Damn those brain worms eh!...
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  10. #10
    Programming Ninja In-T...
    Join Date
    May 2009
    Posts
    827
    What about this?

    Code:
    void FreeMemory(void* mem) {
    
      if (mem) {
        delete mem;
        mem = NULL;
      }
    
    }
    Wont that prevent the crashing if the caller of the function passes an uninitialised pointer?

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    No, since the check is for a null pointer, not "an uninitialised pointer", and there is still the issue of trying to use delete on a pointer to void.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proper Usage of the delete Operator
    By thetinman in forum C++ Programming
    Replies: 7
    Last Post: 04-25-2007, 11:53 PM
  2. C++ Operator Overloading help
    By Bartosz in forum C++ Programming
    Replies: 2
    Last Post: 08-17-2005, 12:55 PM
  3. private overloading of new & delete
    By Aidman in forum C++ Programming
    Replies: 12
    Last Post: 04-28-2005, 01:11 PM
  4. Problem need help
    By Srpurdy in forum C++ Programming
    Replies: 1
    Last Post: 07-24-2002, 12:45 PM
  5. int vs BIG INT
    By rumi_red in forum C++ Programming
    Replies: 1
    Last Post: 10-30-2001, 04:15 AM