6

Cppcheck は、delete cname;. 私のバージョンのコードを使用する際の問題が何であるかわかりません - 動作しているようです。

私のコードは間違っていますか?どうすれば修正できますか?そして、私のコードを使用した結果はどうなりますか?

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

Yes, when you allocate an array using the new …[…] syntax, you should deallocate it using delete[]. In your case, you need delete[] cname;.

If you use the wrong form of delete to match your allocation with new, you have undefined behaviour:

§5.3.5/2 [expr.delete] In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject representing a base class of such an object. If not, the behavior is undefined. In the second alternative (delete array), the value of the operand of delete may be a null pointer value or a pointer value that resulted from a previous array new-expression. If not, the behavior is undefined.

于 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 に答える