BUG OF THE MONTH | CWE-762: Mismatched Memory Management Routines

V611 The memory was allocated using ‘new T[]’ operator but was released using the ‘delete’ operator. Consider inspecting this code. It’s probably better to use ‘delete [] pInlineStorage;’. sphinx.cpp 19178

To begin with, we need to look at the implementation of two macros:

#define SafeDelete(_x) \
  { if (_x) { delete (_x); (_x) = nullptr; } }
#define SafeDeleteArray(_x) \
  { if (_x) { delete [] (_x); (_x) = nullptr; } }

Now, I think you can easily detect the error yourself in this code:

int CSphIndex_VLN::DebugCheck ( FILE * fp )
  CSphRowitem * pInlineStorage = NULL;
  if ( pQword->m_iInlineAttrs )
    pInlineStorage = new CSphRowitem [ pQword->m_iInlineAttrs ];
  // cleanup
  SafeDelete ( pInlineStorage );

As you can see, the memory is allocated as for an array, and is deallocated, as if only one item was created. Instead of macro, SafeDelete the macro SafeDeleteArray should be used here.

Please click here to see more bugs from this project.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.