简体   繁体   中英

If I allocate an a array of objects with operator new[] in C++ but deallocate them individually does it still constitute a memory leak?

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 an int , so it's syntactically invalid to call delete on 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 with delete ). Mixing new[] with delete and new[] with delete results in UB.

You can't mix-and-match either way. If you do, you have undefined behaviour (§5.3.5/2):

In the first alternative ( delete object ), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression , or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.

In the second alternative ( delete array ), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression . If not, the behavior is undefined.

(bold emphasis is mine)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM