What happens when you deallocate a pointer twice or more in C++?

前端 未结 7 2255
自闭症患者
自闭症患者 2020-11-28 09:12
int main() {
    Employee *e = new Employee();

    delete e;
    delete e;
    ...
    delete e;
    return 0;
}
相关标签:
7条回答
  • 2020-11-28 09:51

    It's undefined behavior, so anything can happen.

    What's likely to happen is bad. Typically, the free store is a carefully managed system of free and allocated blocks, and new and delete do bookkeeping to keep everything in a consistent state. If you delete again, the system is likely to do the same bookkeeping on invalid data, and suddenly the free store is in an inconsistent state. This is known as "heap corruption".

    Once that happens, anything you do with new or delete may have unpredictable results, which can include attempting to write outside the application's memory area, silently corrupting data, erroneously thinking there's no more memory, or double or overlapping allocation. If you're lucky, the program will crash soon, although you'll still have problems figuring out why. If you're unlucky, it will continue to run with bad results.

    0 讨论(0)
  • 2020-11-28 09:57

    If you're really lucky it will crash. What normally happens is it stores up karma until your CEO is demonstrating the code to your most important new customer when it will corrupt/destroy all of their data.

    In checked or debug builds often this kind of thing is caught, but it can go completely undetected and cause havoc later. This is especially profound when multiple threads get involved.

    0 讨论(0)
  • 2020-11-28 09:59

    You get undefined behaviour if you try to delete an object through a pointer more than once.

    This means that pretty much anything can happen from 'appearing to work' to 'crashing' or something completely random.

    0 讨论(0)
  • 2020-11-28 10:02

    You are likely venturing into 'undefined behavior' territory.

    On many systems this will cause a crash; for example, on my Linux machine:

    *** glibc detected *** ./cctest: double free or corruption (fasttop): 0x0000000000d59900 ***
    ======= Backtrace: =========
    /lib/libc.so.6[0x7f399f4cbdd6]
    /lib/libc.so.6(cfree+0x6c)[0x7f399f4d074c]
    ./cctest[0x400a7a]
    /lib/libc.so.6(__libc_start_main+0xfd)[0x7f399f474abd]
    ./cctest[0x400959]
    
    0 讨论(0)
  • 2020-11-28 10:02

    It's not safe, and it's undefined what might actually happen:

    http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.2

    0 讨论(0)
  • 2020-11-28 10:06

    If you are worried this might happen in your apps, either stop using raw pointers completely, so that you don't need delete (eg switch over to shared_ptr) or always set pointers to NULL (or 0, or better still nullptr) after you delete them. Calling delete on a null pointer is guaranteed to do nothing.

    0 讨论(0)
提交回复
热议问题