当我们对未分配新运算符的对象的指针使用delete时会发生什么? [英] What happens when we use delete on a pointer to an object not allocated with new operator?

查看:270
本文介绍了当我们对未分配新运算符的对象的指针使用delete时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码编译正常,但不执行

The below code compiles fine but does not execute

#include <iostream>
using namespace std;

int main()
{
    int *a;
    int b = 5;
    a = &b;
    cout << *a << endl;
    delete a;
    return 0;
}

编辑:

int main()
{
    int *a = 0;
    delete a;
    return 0;
}

为什么会这样?

推荐答案

编辑后,你只有一个未定义的行为:
delete c>

After your editing, you only have one case of undefined behaviour: deleteing memory you did not aquire by new.

<$

这篇关于当我们对未分配新运算符的对象的指针使用delete时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆