How do I fix this error with allocation and deallocation mismatch?
Asked Answered
P

2

9

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;
 }      
Permeate answered 1/2, 2014 at 16:21 Comment(1)
Array deallocation is done via "delete [] cname"Dich
M
16

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.

Microclimatology answered 1/2, 2014 at 16:21 Comment(4)
thanks. got it. ohh... really simple. and what is about the consequences of using my version of code?Permeate
@Permeate The most terrible consequence: undefined behaviour.Microclimatology
@Permeate Standard quote has been added to my answer.Microclimatology
Basically, the delete[] variant will call the destructor of each of the array objects. In case of scalar values it might not seem important, but if you are defining an array of classes, the difference is huge.Acute
M
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;
    }    
Mccall answered 1/2, 2014 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.