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

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

    delete e;
    delete e;
    ...
    delete e;
    return 0;
}
7条回答
  •  猫巷女王i
    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.

提交回复
热议问题