1

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 .

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 4
    That is undefined behavior (you are not allowed to do it). –  Jul 17 '17 at 20:10
  • But in codeblocks I am able to insert array of data starting from a single memory allocated . – hasibuzzaman chowdhury Jul 17 '17 at 20:15
  • 3
    @hasibuzzamanchowdhury No you're not, just because it looks like it works doesn't mean it's not undefined. – Hatted Rooster Jul 17 '17 at 20:18
  • 4
    @hasibuzzamanchowdhury -- *But in codeblocks I am able to insert array of data starting from a single memory allocated* -- Think of it this way -- If your driver's license was revoked, does that mean you can't physically get into a car and drive it? Of course you can drive it, but you're not supposed to, as the "undefined behavior" could mean you can drive for hundreds of miles without issues, or drive 100 yards and a policeman stops you right there. – PaulMcKenzie Jul 17 '17 at 20:49
  • If there was just something like a [mcve] and a link to some description [ask] … – too honest for this site Jul 17 '17 at 21:08

3 Answers3

5

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.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
1

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.

0

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>.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165