gpt4 book ai didi

c++ - 使用指针算法时内存泄漏

转载 作者:行者123 更新时间:2023-11-30 02:22:37 25 4
gpt4 key购买 nike

这样的代码会导致内存泄漏吗?

unsigned char *ptr = new unsigned char[2];
ptr++; //pointer now points to the second member of array
delete [] ptr;

最佳答案

根据标准(例如this在线草案版本),delete-ing一个指针的行为,之前没有被new获取,是未定义:

3.7.4.2 Deallocation functions

(3) If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. 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 in the standard library is not one of the values returned by a previous invocation of either operator new or operator new[](std::size_t, const std::nothrow_t&) in the standard library.

ptr+1 的值不是 new[] 返回的值,因此调用 delete[] (ptr+1) 是 UB。任何事情都可能发生,包括它似乎工作正常;但肯定不能保证正常工作

关于c++ - 使用指针算法时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47090640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com