Memory deallocation of pointer variable in c++

If I take a block of memory by the following line .

int* a = new int[10];

Then for freeing the memory , the code would be

delete [] a;

But if I take a pointer of single memory segment like the following

int* a = new int;

And then insert a array of data like following .

for(int i=0;i<10;i++)
 {
    a[i]= i ;
 }

So to free the first memory segment that pointer "a" is pointing, the code would be like following

delete a;

But Here I inserted 9 more data from the memory that pointer "a" is pointing .So I am using actually 10 memory segment here . how can I free all this 10 memory ? Please help me to get the answer .

Upvotes: 1

Views: 174

Answers (3)

Pete Becker
Pete Becker

Reputation: 76235

new int allocates space for one int value. You cannot legally pretend that it's an array of ten int values, and the compiler won't generate code to expand the allocated memory if you go out of bounds. The code you wrote produces undefined behavior. The fact that it compiled and ran doesn't change that; sooner or later it will cause problems.

To allocate an array that can hold 10 int values, use your first expression: new int[10]. That will allocate space for ten int values.

To allocate an array that can be expanded at will, use std::vector<int>.

Upvotes: 0

You allocated only one int. Memory from a[1] to a[9] may be assigned to other objects and you may corrupt them.

P.S. Btw you can not free memory that you did not allocate in any case.

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36463

how can I free all this 10 memory ?

You can't and you shouldn't because the moment you tried to "insert a array of data like following" you have entered Undefined Behavior land for writing to a location that you didn't allocate with new in the first place. You asked for a single int, you got a single int. Don't write past it.

Upvotes: 5

Related Questions