Reputation: 197
If i have something like
int* thing;
thing = new int[10]
(more code...)
thing = new int[50];
would I need to do delete[] thing
between them? And to be sure/safe since I"m posting anyway, there isn't any problems with doing this is there?
Upvotes: 0
Views: 550
Reputation: 96
To be safe you should always delete the memory allocated on the heap, otherwise there will be memory leaks, which in future can lead to memory crunch and can cause your application to crash.
//allocating memory on stack (stack memory will be deleted as soon as it goes out of scope, automatically by the compiler)
int* thing;
//array of 10 is allocated on heap (heap memory is the responsibility of user to delete , otherwise there will be memory leaks)
thing = new int[10]
//Ideally you should delete memory allocated on heap here, otherwise memory leak will be there, which can lead to crunch of memory in future:
(more code...)
delete []thing;
thing = new int[50];
Upvotes: 1
Reputation: 107
Whenever you use new
to allocate memory in the heap, you need to at some point free that memory with delete
. If you don't do this, it will lead to a memory leak. Imagine you allocate 10 spaces to thing
, then "overwrite" it with 50 spaces. Those 10 original spaces get lost somewhere in your memory and never get freed (which is bad).
Upvotes: 0