Reputation: 4281
Tell me what the 3rd line is doing please.
int main(){
int *p = new int[3];
*p++=0; // What's this line doing?
delete p;
return 0;
}
Upvotes: 1
Views: 997
Reputation: 4570
The first element in the array is set to 0 and p is advanced by one to point to the second element.
delete p; // this has undefined behaviour
Use delete [] p;
instead.
Upvotes: 1
Reputation:
*p++=0;
means this:
sizeof(int)
zero bytes to an address stored in p
.p
by sizeof(int)
.In other words — you have incremented the pointer and what you then passing to delete
is not the same as was returned by operator new[]
.
As @FredLarson has also mentioned, you have to use delete [] p;
in order to delete an array.
Also, I'd recommend you read up on pointers, pointer arithmetics and pre-/post-increment. Pick a book from our Definitive C++ Book Guide and List.
Upvotes: 3
Reputation: 4914
You are setting p[0] to 0 and advancing the pointer to p[1]. What are you trying to do?
Upvotes: 0