I know one is supposed to not mix and match new[] with delete and vice versa (delete[] with new). So
int* k = new int[5];
delete k;
is flawed as it will not free the allocated array. But is the following wrong?
int *k = new int[5];
for (int i = 0; i < 5; ++i)
delete k[i];
by wrong I mean – will it actually cause a memory leak or undefined behavior?
EDIT** My bad, what I meant to type was this:
int** k = new int*[5];
memset(k, 0, sizeof(int*)*5);
k[3] = new int;
for (int i = 0; i < 5; ++i)
if (k[i])
{
delete k[i];
k[i] = 0;
}
In the above, the block of 5 places is never actually freed unless i call delete[] on k itself, though I can new/delete manage the ints inside of it.
k[i]is anint, so it’s syntactically invalid to calldeleteon it. The compiler should raise an error.Even if you could, it would result in undefined behavior (saying you have an array of pointers which you allocate with
new[]and attempt to delete it withdelete). Mixingnew[]withdeleteandnew[]withdeleteresults in UB.