#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?
This code is not exception safe – if an exception is thrown between
new[]anddelete[]the block pointed to is leaked. Usestd::vectorto resolve this problem.