gpt4 book ai didi

c++ - 是否需要在原始指针位置调用delete[]

转载 作者:行者123 更新时间:2023-12-02 02:49:35 24 4
gpt4 key购买 nike

根据这个问题的答案:“How does delete[] "know" the size of the operand array?

your allocator will keep track of how much memory you have allocated

How free knows how much memory to deallocate"

Yes, the memory block size is stored "somewhere" by malloc (normally in the block itself), so that's how free knows. However, new[]/delete[] is a different story. The latter basically work on top of malloc/free. new[] also stores the number of elements it created in the memory block (independently of malloc), so that later delete[] can retrieve and use that number to call the proper number of destructors

这是否意味着delete[] 与指针指向的位置无关?以下代码有效还是会导致内存泄漏?

void createArray(){
char* someArray = new char[20];
readData(someArray);
//Is this delete still valid after moving the pointer one position?
delete[] someArray;
}

char readData(char* &arr){
char value = *arr;
//Let it point to the next element
arr += 1;
return value;
}

最佳答案

是的,确实如此。如果您更改 new[]-ed 指针值,然后对其调用 delete[] 运算符,您将调用未定义的行为:

char* someArray = new char[20];
someArray++;
delete[] someArray; // undefined behavior

而是将原始值存储在不同的指针中并对其调用delete[]:

char* someArray = new char[20];
char* originalPointer = someArray;
someArray++; // changes the value but the originalPointer value remains the same
delete[] originalPointer; // OK

关于c++ - 是否需要在原始指针位置调用delete[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48322684/

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