new,delete, malloc, free

今天我在写程序的时候,把一个new出来的指针ptr delete了两次,结果导致程序运行一会就crash,用gdb调式了一下发现时内存访问错误,但每次发生错误的地方都不一样,而且有点莫名奇妙。找了好久,后来才发现时delete了两次,那么第二次delete ptr的时候,这块内存其实已经分配给其他变量了,所以就把其他的变量的内存空间给delete了,当然会crash。所以良好的风格是

if(ptr)

{

    delete ptr;

    ptr = NULL;

}

把ptr赋为NULL之后,多次delete其实是没有关系的,当然加上判断是最好的,逻辑上显得比较清晰,但一定要在delete之后赋值为NULL。

 

不管是malloc 还是 new,分配的空间都是4或8的整数倍,如malloc(3),那么系统至少返回的空间大小是4


malloc 和 new 都可以申请分配大小为0的对象,例如

int *pi = new int[0];

int *pj = (int *)malloc(sizeof(int) * 0);

那么申请size 为0的对象会有什么结果呢,C++标准规定申请内存成功不能返回空指针(当然可以失败),也就是说虽然我们申请了int[0],但只要成功也是返回非空指针,而malloc可以返回空也可以返回非空,这个要看具体库的实现,但一般是返回非空的,我在suse linux下试验了一把是返回非空的。那么为什么呢?

1)首先 size 0的对象也是对象,也可以申请

2) 如果返回空指针,容易和申请失败混淆

3)即便返回一个指针,这个指针也是不可读写的,系统不用进行多余的操作,一般都是返回一个固定的地址,也没有多大的开销

只要我们申请成功了,都是可以调用free 或 delete来释放的

摘自C99标准:7.20.3

Memory management functions If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
从上面的规定可以看出 malloc(0) 不一定能分配到空间。

摘自C++标准:
Even if the size of the space requested is zero, the request can fail. If the request succeeds,the value returned shall be a nonnull
pointer value (4.10) p0 different from any previously returned value p1, unless that value p1 was subsequently passed to an operator delete. The effect of dereferencing a pointer returned as a request for zero size is undefined.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值