c++ - 这是否包含内存泄漏?

标签 c++ memory-leaks new-operator dynamic-memory-allocation memmove

<分区>

下面的代码是否包含内存泄漏。我怀疑它确实如此,但我用来检测它们的工具(Visual Studio + Parasoft c++ 测试)没有标记任何东西。如果是我该如何解决?

//A dynamically allocated array of char pointers
int numOfStrings = 10, numOfChars = 32;
char** data = new char*[numOfStrings];

//Generate each each individual string
for(int i = 0; i <numOfStrings; i++)
    data[i] = new char[numOfChars];

//moves the elements 1-5 in the array to the right by one
int index = 1, boundary = 5, sizeToMove = (boundary - index) * sizeof(numOfChars);
memmove(&data[index + 1],&data[index],sizeToMove);

delete[] data;

编辑:

我应该提一下,我试过如下遍历每个单独的字符串,但发生了异常。

for(int i = 0; i< numOfStrings; i++)
    delete [] data [i];

最佳答案

是的。删除时

delete[] data;

您正在释放为数据分配的内存。但是分配的内存

data[i] = new char[numOfChars];

还没有被释放。

在删除数据之前,您必须遍历 data 并删除每个 data[i]

通常,您应该确保您拥有的delete数量与new数量一样。
这里有 numOfStrings + 1 new 和只有一个 delete

又一次泄漏

既然你在做

int index = 1, boundary = 5, sizeToMove = (boundary - index) * sizeof(numOfChars);
memmove(&data[index + 1],&data[index],sizeToMove);

(您没有像您想象的那样移动 5 个位置,而是移动 4 个位置 (5 - 1 = 4))

此操作后

data[2] will get the value of data[1]

data[2] <- data[1]
data[3] <- data[2]
data[4] <- data[3]
data[5] <- data[4]

data[5] 指向的内容将会丢失。
data[2], data[1] 会有相同的值(指向同一个地方)

这也可以解释为什么当您想通过遍历 data 进行删除时会出现段错误

关于c++ - 这是否包含内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15749391/

相关文章:

javascript - ExtJS 堆快照.. 我什么时候应该开始担心?

c++ - 为什么堆上的分配比栈上的分配快?

c# - 函数的 "static new"修饰符有什么意义?

c++ - C++ 代码编译期间的段错误(核心转储)错误消息

c++ - header 中包含的函数未执行,但没有编译错误

c++ - 是否有 std::lock_guard<std::mutex> lock(m) 的简写?

memory - iOS 6,崩溃并出现内存不足警告

c++ - 在 C++ vector<T> 中释放内存

swift - swift 中的运算符或方法,作为 python 的海象运算符

c++ - 成员模板,来自 ISO C++ 标准的声明?