【发布时间】:2013-03-22 21:05:02
【问题描述】:
下面的代码是否包含内存泄漏。我怀疑确实如此,但我用来检测它们的工具(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];
【问题讨论】:
-
@NuclearGhost:不,不应该。这个问题是关于识别和纠正一段代码中的特定问题。代码审查适用于当您有一段代码需要在任何领域提出改进建议时。
-
不要使用
new;最好使用std::vector,或者chars的情况下,std::string。
标签: c++ memory-leaks new-operator dynamic-memory-allocation memmove