Heap corruption after new char[strlen

Heap corruption after new char[strlen

本文关键字:strlen char new corruption after Heap      更新时间:2023-10-16

目前正在编写一些代码,这些代码在调试环境中的Win XP和Win 7上运行。但它在相关版本中的一些地方失败了,堆损坏。非常感谢你的帮助。

char *strr = NULL;
if (SomeValue!= NULL)
{
      while(SomePos != NULL)
    {
        CString strTemp; double SomeAmount; 
        strTemp.Format("%f",SomeAmount );
        strr = new char[strlen((LPCTSTR)strTemp + 1)];
        strcpy(strr,LPCTSTR(strTemp));
        if(strr)
        {
            strr = NULL;
            delete[] strr;
        }
     }
}

看到这里,我可以发现在删除字符指针时遗漏了一些东西。

括号放错地方了。你想写:

strlen((LPCTSTR)strTemp) + 1

因此,您将分配一个比需要的短两个字符的缓冲区

使用GetLength()方法更有意义:

strr = new char[strTemp.GetLength() + 1)];

这个代码显然是错误的:

strr = NULL;
delete[] strr;

当然,您不能期望在NULL上使用delete[]

我想你的意思是:

strr = new char[strlen((LPCTSTR)strTemp) + 1];

这个+1代表"\0",对吗?