Reputation: 73
#include <iostream>
using namespace std;
int main()
{
int i,j;
int * k;
char m;
do{
cin >> j;
k = new int[j];
for (i = 0; i < j; i++){
k[i] = i;
cout << k[i] << ", ";
}
delete[] k;
cout << "\nContinue?\n";
cin >> m;
}while (m != 'n');
}
This is a program I made to describe my problem in understanding new
and delete
. Will 'k' produce memory leak?
Upvotes: 0
Views: 142
Reputation: 16195
No, it will not in this instance as you free the memory within the loop. However, you'd be much better of using a scoped_array in this instance.
Upvotes: 0
Reputation: 412
As already pointed out by sharptooth, you should use a try-catch block to make sure any exception is caught and k
is released.
In a general case, you can use valgrind to check if your program is freeing all blocks that were allocated during execution.
Upvotes: 1
Reputation: 170469
This code is not exception safe - if an exception is thrown between new[]
and delete[]
the block pointed to is leaked. Use std::vector
to resolve this problem.
Upvotes: 11