gpt4 book ai didi

c++ - 可能的内存泄漏?

转载 作者:太空宇宙 更新时间:2023-11-04 15:51:35 25 4
gpt4 key购买 nike

我有以下代码:

void customHandleException  (_EXCEPTION_POINTERS* ExceptionInfo)
{
char* x = (char*)ExceptionInfo->ExceptionRecord->ExceptionInformation[0];
delete[] x;
}


void foo()
{
char* x = new char[ 256 ];
ULONG_PTR* args = new ULONG_PTR[1];
args[0] = (long)x;
RaiseException(EXCEPTION_CODE,0,1,args);
}

撇开所有其他因素不谈,customHandleException() 中的char* x 将指向在foo() 中分配的char 数组。这会导致内存泄漏还是删除会起作用?

最佳答案

您应该使用 delete[]。用new[]分配的内存必须delete[]释放。

引用:

C++03 标准:§ 3.7.4.2-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 value supplied to operator delete(void*) in the standard library shall be 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 value supplied to operator delete[](void*) in the standard library shall be 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.

关于c++ - 可能的内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7419078/

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