1
votes

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;   
}
3
You should be more concerned about the line that follows that one. - chris
What's it doing? It is invoking the dreaded undefined behavior. Prepare for a high risk of nasal demons. - dmckee --- ex-moderator kitten

3 Answers

3
votes

*p++=0; means this:

  1. Write sizeof(int) zero bytes to an address stored in p.
  2. Increment the value of 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.

1
votes

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.

0
votes

You are setting p[0] to 0 and advancing the pointer to p[1]. What are you trying to do?