修改字符串结尾时delete []的行为是什么

时间:2014-08-08 08:02:00

标签: c++

请考虑以下代码:

char * storedString = NULL; //Global Variable
void storePlainStringAndProcess(char* delimitedString) //assume string "Apple,"
{
    int len = strlen(delimitedString);
    storedString = new char[len + 1];
    strcpy(storedString, delimitedString);

    storedString[len - 2] = '\0';   //removing the trailing comma, resulting string "Apple"
    //........<some code>.......//
    delete [] storedString;
}

我构建此代码只是为了了解在这种情况下删除的行为。当字符串在结尾处被修改并终止时,分配的空间会发生什么?会有内存泄漏吗?

1 个答案:

答案 0 :(得分:4)

不会有内存泄漏。当您编写new char[时,C ++运行时会记住您已分配的内存量。

当你delete[]时,就会释放出足够的内存量。 (要非常清楚,空终止符用于确定要释放的内存量。)

这就是将new[]delete[]匹配至关重要的原因。实际上,使用不带括号的delete时的行为是未定义