Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cppcheck thinks there is a mismatch in alloc and dealloc

Tags:

c++

cppcheck

The cpp-check error is: error mismatchAllocDealloc false Mismatching allocation and deallocation: val2

What should I do to fix this error?

void MainWindow::ParseDemo(char *pBuf)
{
  char* val2 = new char[256];
  for (int i = 0; i < 254; i++)
  {
     val2[i] = pBuf[i+305];
  }
  val2[254] = 0; // 0-Termination
  QString sunit(val2);
  DoStuff(sunit);
  delete val2;
  // ... 
}
like image 712
S.Spieker Avatar asked Sep 04 '26 17:09

S.Spieker


1 Answers

error mismatchAllocDealloc false Mismatching allocation and deallocation: val2

new and new [] need to be used in a consistent manner with delete and delete [], that's why cppcheck complains.

What should I do to fix this error?

Write delete [] val2;, that should fix it.

BTW, that's not indicating a memory leak directly, but it could become one easily, because it's basically undefined behavior.

like image 193
πάντα ῥεῖ Avatar answered Sep 07 '26 09:09

πάντα ῥεῖ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!