加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 内存是否泄漏?

发布时间:2020-12-16 10:22:45 所属栏目:百科 来源:网络整理
导读:我在一个更大的代码中间有一小段代码: int *p = new int[100];p += 50;delete []p; 编译器是否只删除第51个位置的内存?我认为确实如此.但是,在数组指针的情况下,编译器会保存一个附加项,该项指示已分配的对象数.那么,在这种情况下,是否应该继续删除超出分
我在一个更大的代码中间有一小段代码:

int *p = new int[100];
p += 50;
delete []p;

编译器是否只删除第51个位置的内存?我认为确实如此.但是,在数组指针的情况下,编译器会保存一个附加项,该项指示已分配的对象数.那么,在这种情况下,是否应该继续删除超出分配大小的内存?
或者它是否删除第51个第100个元素并将第1个-50位保留在内存中,在这种情况下可能发生内存泄漏.

解决方法

这是未定义的行为. The C++ standard says:

3.7.4.2 Deallocation functions

3 … Otherwise,the behavior is unde?ned
if the value supplied to operator delete(void*) in the standard library is not 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,and the behavior is unde?ned if the value supplied to operator
delete[](void*)
in the standard library is not 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.

4 … The e?ect of using an invalid pointer value (including passing it to a deallocation function) is unde?ned. (On some implementations,it causes a system-generated runtime fault.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读