6

Cppcheck report as an error "Mismatching allocation and deallocation: cname" for the line with delete cname;. I don't see what the problem with using my version of code is - it looks working.

Is my code wrong? How do I fix it? And what are the consequences of using my code?

if ( lenght != 0 )
{
   char *cname = new char[lenght+1];    
   inbin.read(reinterpret_cast<char *>( cname ), lenght );
   cname[lenght] = '\0';
   *ptr_string = cname;             
   delete cname;
 }      
4

2 回答 2

14

是的,当您使用语法分配数组时new …[…],您应该使用delete[]. 在您的情况下,您需要delete[] cname;.

如果你使用错误的形式delete来匹配你的分配new,你有未定义的行为:

§5.3.5/2 [expr.delete]在第一种选择(删除对象)中,操作数的值可以是空指针值、指向由先前的新表达式delete创建的非数组对象的指针,或指向表示此类对象的基类的子对象的指针。如果不是,则行为未定义。在第二种选择(删除数组)中,操作数的值可以是空指针值或由前一个数组new-expression产生的指针值。如果不是,则行为未定义。delete

于 2014-02-01T16:21:50.383 回答
1
if ( lenght != 0 )
    {
        char *cname = new char[lenght+1];   
        inbin.read(reinterpret_cast<char *>( cname ), lenght );
        cname[lenght] = '\0';
        *ptr_string = cname;                
        delete[] cname;
    }    
于 2014-02-01T16:24:49.463 回答