Sign in to follow this  
tomneo2004

[Help] delete dynamic array

Recommended Posts

aa=new int[2] creates an array of length 2 - a[0] and a[1]. You then access a[2], which would be the third element, hence your crash.

It's the classic confusion with counting from zero - your last valid array index is always one less than the size of the array.

Share this post


Link to post
Share on other sites
You allocate a vector with two elements but then write to a third element. The debug runtime detects that you have written beyond the boundaries on the call to delete and raises the warning you see.

Share this post


Link to post
Share on other sites
Quote:
Original post by tomneo2004
ok thanks guys but if i change int type to the type that define by myself is it possible to use delete[] to clear array?
No, delete[] will destruct elements and deallocate the array. It is possible to override the new and delete operators but clearing arrays is still not what they're for.

I recommend you look into using std::vector instead, for one thing this can clear itself.

Share this post


Link to post
Share on other sites
Quote:
Original post by tomneo2004
ok thanks guys but if i change int type to the type that define by myself is it possible to use delete[] to clear array?

What exactly do you mean by "clear"? After delete[], the array won't exist anymore.

Share this post


Link to post
Share on other sites
Quote:
Original post by dmatter
I recommend you look into using std::vector instead, for one thing this can clear itself.

Excellent suggestion. The program would then look like this:

#include <iostream>
#include <vector>

int main()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
std::cout << vec[2] << std::endl;
}


Note the abscence of manual memory management. No more new[] and delete[], and you don't have to worry about how large the vector needs to be.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this