In C++ is there any difference between the pointers p and q in the below code?
There is no visible difference between the pointers, but there certainly is one, and it is important. One is a pointer to an integer, the other is a pointer to an integer, which is also the first element in an array of a given size.
Unluckily, given only the pointer, you have no way of telling.
What would happen if I used delete q?
Probably nothing, but possibly a lot.
First of all, calling delete
instead of delete[]
will call the destructor exactly once, on the first element of the array, rather than on every element as it should. Now, the destructor for a trivial type like int
doesn't do anything, so... as far as that goes, there is no real difference. There is, however, a huge difference for not-so-trivial types where the destructor (or chain of destructors) actually does something.
Second, you are interfering with proper deallocation of the underlying raw memory block. This can (and sometimes does) cause a hard crash. It might even cause a crash which occurs at a later time, in an unrelated, innocent piece of code, due to corruption earlier. Try and debug that.
Or, you might get a silent memory leak, it depends on the implementation and sometimes even on your "luck" in the particular case (e.g. hit a page boundary or not).
Because, well, allocating and freeing an array and allocating and freeing a single element just isn't the same thing. They are (usually) implemented slightly differently, and while the implementation may be able to cope with mismatched new
/delete
, that isn't guaranteed. You might get different behavior in the debugger compared to normal exection, too, whatever, anything.
Calling the wrong form of delete
means invoking undefined behavior. Which basically means anything can happen. That includes "nothing" as well as "problem which is impossible to debug". It also includes the possibility of the compiler optimizing maliciously or just stripping out the entire surrounding function, or assuming a certain condition to be always-true. Which can lead to very nasty surprises on which you spend days and days trying to figure out what's going on.