0

Let's suppose the following code:

    int* ptr = new int[10];
    ...
    ...
    ptr += 2;
    delete[] ptr;
    ptr = NULL;

Should ptr be pointing on the first element of the array when the delete is called?

apxcode
  • 7,696
  • 7
  • 30
  • 41
  • 6
    `delete` what you `new`. Nothing else. – chris Jun 29 '14 at 03:15
  • 1
    Are you facing any actual problems with your code? If so elaborate in your question, if not you're off-topic here :-/ ... – πάντα ῥεῖ Jun 29 '14 at 03:20
  • 1
    '_Should ptr be pointing on the first element of the array when the delete is called?_' Certainly, YES! – πάντα ῥεῖ Jun 29 '14 at 03:21
  • Also, take a look at http://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array and http://stackoverflow.com/questions/703691/how-does-delete-know-its-an-array-c for more info. – R Sahu Jun 29 '14 at 04:21
  • @πάντα ῥεῖ the question's not off topic... the "actual problem" is obviously knowing whether the code has defined behaviour, deleting the array as clearly intended. It's probably a duplicate and could have been resolved by a quick look at the Standard or many online references, but that's not unique to this question.... – Tony Delroy Jun 29 '14 at 04:46

1 Answers1

3

If you call delete on something that you didn't get back from new, that's undefined behavior.

So the result of the following code is undefined:

int* ptr = new int[10];
ptr += 2;
delete[] ptr;

Let's look at the standard as well:

C++ 2011. Section 3.7.4.2 Deallocation functions. Paragraph 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.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173