Reputation: 1267
Here is the code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
int *p = new int[2];
p[0] = 1;
p[1] = 2;
cout << *p++ << endl;
delete p;
return 0;
}
It can be compiled, but got a runtime error "free(): invalid pointer", followed by a memory map.
operating system ubuntu 10.10
compiler: g++ 4.4.3
Upvotes: 0
Views: 1594
Reputation: 352
Your call to delete
must use the same pointer returned by your call to new
.
In your code, you increment p
with *p++
, which due to operator precedence is interpreted as *(p++)
. Due to this, you are providing delete
a pointer that the memory manager has never heard of.
Additionally, you should use delete[]
to match a call to new[]
.
That being said, here is a guess of what you may have intended:
int *p = new int[2];
p[0] = 1;
p[1] = 2;
for(int i = 0; i < 2; i++)
cout << p[i] << endl;
delete[] p;
return 0;
Upvotes: 3
Reputation: 10557
Look a the code:
int *p1 = new int;
int *p2 = new int[2];
int *p3 = p1;
int *p1 = p2;
delete p3;
delete[] p1;
Pointers p1
and p2
have the same representation and the same set of allowed operations. For the compiler they are both int*
.
Althougth the objects that they are pointing at are significantly different. The object from new int[2]
at hegative offset has a header that contains the number of items in the array.
Working with array object is the same as if it were a scalar object. Only when this object is released, it is necessary to tell the compiler what sort of object is it. A simple object or an array. This is known source of bugs and confusion. Neverthless the language was defined in this way decades ago and we cannot change this.
It is also important to delete
exactly the same pointer that was returned with new
. This rule applies both to simple new
and new[]
.
Upvotes: 1
Reputation: 888107
You need to call the array-version of delete
:
delete[] p;
EDIT: However, your real problem is that you're incrementing p
.
The delete
operators only work on the original pointers that were allocated.
Upvotes: 6