Click here to Skip to main content
15,880,854 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
C++
int main(int argc, char* argv[])
{
	int* p = new int[10];
	for (int i = 0; i < 12; ++i) {
		p[i] = i;
	}
	delete []p;
	return 0;
}


g++ raise an error:

"*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x00000000019f9010 ***" and exit


VS2008 can not exit when delete []a, I don't know what happened in background.

I have some questions.
1. What's the difference between delete and delete[] ?
2. How does the compiler know the size of a array when using delete [] ?
3. Like the example, p has two elements overloaded, How does the compiler know the tail of p and stop deleting.

Thanks for your attention.
Posted
Updated 25-Sep-14 23:01pm
v2

The error is clear, I think: just change

C++
//for (int i = 0; i < 12; ++i)

for (int i = 0; i < 10; ++i)


or change the size of array to 12.

1. The difference between delete and delete[]

From the standard (5.3.5/2) :

In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined.

In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behavior is undefined.

2, 3. How does the compiler know the size of a array when using delete [] ?
How does the compiler know the tail of p and stop deleting?

It is unspecified how the size information is stored, so each compiler may implement it in a different way, but a common way to do it is to allocate an extra block before the array. That is, when you do this:

C++
int* p = new int[10];


it actually allocates an array of 11 integers, and stores the array size in the first element
 
Share this answer
 
v3
Comments
cxxxxf 27-Sep-14 21:53pm    
Thanks. Further question, is the array size stored in p[-1] which is overwrote? As a consequence, the compiler can not know the array size and raise error(in g++) or do not exit (in vs2008) ?
Leo Chapiro 28-Sep-14 3:37am    
Yes, exactly!
1. If you used new use delete, if you used new[] then use delete[].

http://stackoverflow.com/questions/4255598/delete-vs-delete[^]

2. How the compiler knows is compiler dependent.

http://stackoverflow.com/questions/975792/how-does-delete-know-the-size-of-an-array[^]

3. See above
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900