【问题标题】:Exception during delete[] after memmove在 memmove 之后删除 [] 期间出现异常
【发布时间】:2013-04-01 19:30:50
【问题描述】:

我有下面的代码,其中包含一个动态的字符串数组。我在解除分配生成的每个单独字符串时遇到问题。我以为我可以只包含一个新的 for 循环来释放它们,但这不起作用。我该怎么做?

//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);

for(int i=0;i < numOfStrings; i++)
delete [] data[i];   //this line is causing an exception on its first call (I've also tried delete data[i].

delete[] data;

【问题讨论】:

  • 使用C++的工具会容易很多。 std::vector&lt;std::string&gt; data(numOfStrings);
  • 您正在移动数组本身的内存,您不想获取数据的地址,而是获取数据指向的指针。还要检查你的 sizeof(numOfChars) 因为它相当于 sizeof(int) 你确定你想要那个吗?

标签: c++ arrays memmove


【解决方案1】:

除了顾名思义之外,memmove 实际上并没有“移动”字节。它复制它们(但是,与memcpy 相比,即使源区域和目标区域重叠,它也可以正确执行此操作)。

因此,在将内容从源区域“移动”到目标区域之后,那些位于不重叠部分的元素仍然保持不变。特别是,data[index] 没有改变,因此与memmove() 之后的data[index+1] 的内容相同。

因此,任何对delete [] data[index+1] 的尝试都会尝试释放与delete [] data[index] 相同的内存。这是违法的。

为解决此问题,需要在移动后将data[index](或通俗地说,源区域的任何不重叠部分)设置为0(或nullptr),或采取其他措施确保它没有被删除。

根据您的代码,最简单的直接修复方法是插入

data[index] = 0;

在删除循环之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2011-07-29
    相关资源
    最近更新 更多