新char之后堆积腐败[strlen

WEN*_*zER 1 c++

目前正在研究一些代码,这些代码在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;
        }

     }
}
Run Code Online (Sandbox Code Playgroud)

看这个我可以弄清楚在删除char指针时遗漏了一些东西.

Dav*_*nan 11

你的括号在错误的地方.你打算写:

strlen((LPCTSTR)strTemp) + 1
Run Code Online (Sandbox Code Playgroud)

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

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

strr = new char[strTemp.GetLength() + 1)];
Run Code Online (Sandbox Code Playgroud)

这段代码显然是错误的:

strr = NULL;
delete[] strr;
Run Code Online (Sandbox Code Playgroud)

当然,你不能指望使用delete[]NULL.


mar*_*inj 7

我想你的意思是:

strr = new char[strlen((LPCTSTR)strTemp) + 1];
Run Code Online (Sandbox Code Playgroud)

这个+1是'\ 0'对吗?