# problem with deallocation

## Recommended Posts

Watchman234    122
Im trying to deallocate the address of one arrays index and a runtime error occured :(. here is the code i have tried to compile: int *x = new int[3]; x[0] = 1; x[1] = 2; x[2] = 3; delete (x+1); I dont understand why its not working , cant i just delete one index of the array?

##### Share on other sites
Gage64    1235
When you call delete on an address of an object that was allocated with new, that address has information required to do the deallocation properly (or rather, the compiler knows how to get that information given the address). What you are calling delete on is not such an address.

Also, when an array is allocated, it is allocated as one big chunk of memory. You can't delete just a part of that chunk. Why do you want to delete just "one index" anyway?

##### Share on other sites
rip-off    10976
Quote:
 Original post by Watchman234Im trying to deallocate the address of one arrays index and a runtime error occured :(.here is the code i have tried to compile: int *x = new int[3];x[0] = 1;x[1] = 2;x[2] = 3;delete (x+1);I dont understand why its not working , cant i just delete one index of the array?

Nope. You can only pass to delete what you got from new, and to delete [] what you got from new [].

However, you would be better served by using a container class like std::vector:
#include <vector>std::vector x(3); // vector with initial size 3for( int i = 0 ; i < x.size() ; ++i ) { x[i] = i; }x.erase( x.begin() + 1 );

##### Share on other sites
Watchman234    122
ok , thanks.