Calling delete on variable allocated on the stack

58,389

Solution 1

No, it is not safe to call delete on a stack-allocated variable. You should only call delete on things created by new.

  • For each malloc or calloc, there should be exactly one free.
  • For each new there should be exactly one delete.
  • For each new[] there should be exactly one delete[].
  • For each stack allocation, there should be no explicit freeing or deletion. The destructor is called automatically, where applicable.

In general, you cannot mix and match any of these, e.g. no free-ing or delete[]-ing a new object. Doing so results in undefined behavior.

Solution 2

Well, let's try it:

jeremy@jeremy-desktop:~$ echo 'main() { int a; delete &a; }' > test.cpp
jeremy@jeremy-desktop:~$ g++ -o test test.cpp
jeremy@jeremy-desktop:~$ ./test
Segmentation fault

So apparently it is not safe at all.

Solution 3

Keep in mind that when you allocate a block of memory using new (or malloc for that matter), the actual block of memory allocated will be larger than what you asked for. The memory block will also contain some bookkeeping information so that when you free the block, it can easily be put back into the free pool and possibly be coalesced with adjacent free blocks.

When you try to free any memory that you didn't receive from new, that bookkeeping information wont be there but the system will act like it is and the results are going to be unpredictable (usually bad).

Solution 4

Yes, it is undefined behavior: passing to delete anything that did not come from new is UB:

C++ standard, section 3.7.3.2.3: The value of the first argument supplied to one of thea deallocation functions provided in the standard library may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_t&) in the standard library.

The consequences of undefined behavior are, well, undefined. "Nothing happens" is as valid a consequence as anything else. However, it's usually "nothing happens right away": deallocating an invalid memory block may have severe consequences in subsequent calls to the allocator.

Solution 5

After playing a bit with g++ 4.4 in windows, I got very interesting results:

  1. calling delete on a stack variable doesn't seem to do anything. No errors throw, but I can access the variable without problems after deletion.

  2. Having a class with a method with delete this successfully deletes the object if it is allocated in the heap, but not if it is allocated in the stack (if it is in the stack, nothing happens).

Share:
58,389

Related videos on Youtube

unistudent
Author by

unistudent

Updated on July 05, 2022

Comments

  • unistudent
    unistudent almost 2 years

    Ignoring programming style and design, is it "safe" to call delete on a variable allocated on the stack?

    For example:

       int nAmount;
       delete &nAmount;
    

    or

    class sample
    {
    public:
        sample();
        ~sample() { delete &nAmount;}
        int nAmount;
    }
    
    • jdt141
      jdt141 over 15 years
    • Drew Dormann
      Drew Dormann over 15 years
      Note that your second example doesn't have to be on the stack. nAmount would be local to whatever memory sample exists in.
    • paxdiablo
      paxdiablo over 15 years
      About as safe as poking a sharp needle in your eye.
    • BЈовић
      BЈовић over 11 years
      nasal demons - this is what happens
    • Tadeusz Kopec for Ukraine
      Tadeusz Kopec for Ukraine over 11 years
      One kitten gets killed somewhere.
  • unistudent
    unistudent over 15 years
    Thanks! My compiler didn't seg fault but I was definitely suspicious if it was legitimate.
  • jcopenha
    jcopenha over 15 years
    "Should" is a better word. "Must" implies that the malloc/new/new[] will fail if the free/delete/delete[] is absent, which is not the case. The use of "exactly one" carries the implication I think you are going for.
  • dtech
    dtech over 11 years
    OK, supposedly I have a hierarchy tree of parent/child objects. The tree is responsible for recursively invoking different object methods and upon deletion of a root object all children should get recursively deleted. However some of the children may be scope allocated, others dynamically, in this case it is not possible to distinguish between the two and only delete dynamic objects without adding some more data to specify it?
  • Mike Seymour
    Mike Seymour over 11 years
    @ddriver: No, it's not possible to get that information given just a pointer. You could use std::shared_ptr with a custom deleter that does nothing to non-dynamic objects, or add your own metadata, or come up with a less convoluted lifetime management strategy.
  • ereOn
    ereOn over 11 years
    @ddriver: I usually go by a simple rule: The object or scope that is responsible for an object creation is also responsible for its deletion. Or put it otherwise: don't delete an object you haven't newed in the first place.
  • Admin
    Admin over 11 years
    @ddriver if you need this, your design is seriously flawed. Rethink it, this should not be a problem.
  • dtech
    dtech over 11 years
    @MikeSeymour, rest - I am asking mostly because I am curious of how this scheme works in Qt, where QObject can accept both stack and heap objects for children, and supposedly when the parent is deleted, it goes through and deletes the entire tree. And the tree itself is not only designed for lifetime management, there is all kind of functionality that can be ran on the tree recursively.
  • Admin
    Admin over 11 years
    "and supposedly" - so not actually.
  • dtech
    dtech over 11 years
    Supposedly as in possibly, not as in "not actually" - that is what the documentation says. "The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor."
  • Admin
    Admin over 11 years
    @ddriver oh, that's different. (For me, supposedly means that you think it is, sorry.)
  • dtech
    dtech over 11 years
    Maybe I will have better chances for an answer if I move it to a new question and focus on that instead of starting at the bottom, i.e. what happens when calling delete on a stack object.
  • Andreas Fester
    Andreas Fester over 11 years
    @ddriver: Where did you get the QObject stuff from? In the Qt API docs, at QObject::~QObject(), it clearly says: Warning: All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash.
  • Joey Carson
    Joey Carson about 10 years
    Your answer is actually relevant to the question. There are always too many evangelist programmers on SO condemning anyone who asks a question out of their own sheer curiosity (the reason I'm here) as to what the standard is that should occur in unexpected corner cases of a language.
  • cdhowie
    cdhowie over 9 years
    I know this is an old answer, but I feel compelled to comment that trying something may not be the best way to prove that it is safe; if it worked, that would not imply that the operation is safe or that the behavior is well-defined, it would just prove that it worked that one time. (You can prove this way that things don't work but the inverse does not always hold.)
  • jwg
    jwg over 8 years
    @cdhowie This is an irrelveant remark. Trying something and finding that it is unsafe does prove that it is unsafe. This is what the answer does. If the answerer hadn't found his example to segfault, he might have simply not posted it. You don't know how many things he tried before reaching that example.
  • RecursiveExceptionException
    RecursiveExceptionException almost 7 years
    @jwg I don't think you got cdhowies point. There are many things in C++ that are not safe but can work. I'm sure you can find a compiler that produces code that doesn't segfault because they thought it would be a great feature. Everything works just great. Now you switch compiler and notice that just because you didn't get an error with the previous compiler doesn't mean that your code isn't bad and unable to work with any other compiler. Computer science is more complex than 'It worked this time so it must be perfectly fine.' Not even to mention the concept of "Undefined Behaviour"
  • RecursiveExceptionException
    RecursiveExceptionException almost 7 years
    @jwg To be fair, I think I did.