3

I have this small piece of code in the middle of a larger code:

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

Will the compiler delete only the memory from the 51st location? I think it does. However, in the case of array pointers, the compiler holds an additional item which tells the number of objects allocated. So, in that case, shouldn't it go ahead and delete memory beyond the allocated size? Or does it delete the 51st–100th elements and keep the 1st–50th in the memory, in which case a memory leak can happen.

4

3 回答 3

6

It's actually undefined behavior. You can only delete / delete[] what you got from new / new[].

于 2012-08-26T12:10:06.937 回答
5

It's undefined behavior. 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.)

于 2012-08-26T12:14:39.867 回答
1

The compiler does not allocate or delete memory, it is OS-dependent what happens if you call free on a pointer value that you did not get from new. The only thing that is guaranteed is that it is wrong.

于 2012-08-26T12:12:01.100 回答