微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 内存是否泄漏?

我在一个更大的代码中间有一小段代码

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 undefined
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 undefined 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 effect of using an invalid pointer value (including passing it to a deallocation function) is undefined. (On some implementations,it causes a system-generated runtime fault.)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐