Arch1tect
Arch1tect

Reputation: 4281

Pointer being freed was not allocated?

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

Answers (3)

Yang Zhang
Yang Zhang

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

user405725
user405725

Reputation:

*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.

Upvotes: 3

robert_difalco
robert_difalco

Reputation: 4914

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

Upvotes: 0

Related Questions