如果我在C ++中使用运算符new []分配了一个对象数组,但分别取消分配了它们,是否仍构成内存泄漏? [英] If I allocate an a array of objects with operator new[] in C++ but deallocate them individually does it still constitute a memory leak?

查看:48
本文介绍了如果我在C ++中使用运算符new []分配了一个对象数组,但分别取消分配了它们,是否仍构成内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道应该不将new []与Delete混合和匹配,反之亦然(将new []与new混合).所以

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;
    }

在上面的方法中,除非我可以在k本身上调用delete [],否则实际上不会释放5个位置的块,尽管我可以新建/删除来管理其中的整数.

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]int,因此在其上调用delete 在语法上无效.编译器应该引发错误.

k[i] is an int, so it's syntactically invalid to call delete on it. The compiler should raise an error.

即使可能,也会导致未定义的行为(假设您有一个指针数组,并使用new[]进行了分配,并尝试使用delete删除它).将new[]deletenew[]delete混合会生成UB.

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.

这篇关于如果我在C ++中使用运算符new []分配了一个对象数组,但分别取消分配了它们,是否仍构成内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆