V630. The 'malloc' function is used to allocate memory for an array of objects which are classes containing constructors/destructors.

The analyzer has detected a potential error caused by using one of the dynamic memory allocation functions such as malloc, calloc, realloc. The allocated memory is being handled as an object array that has a constructor or a destructor. When memory is allocated for the class in this way, the code does not call the constructor. When memory is released through the 'free()' function, the code does not call the destructor. This is quite odd: such a code might cause handling uninitialized variables and other errors.

Consider an example of incorrect code:

class CL
  int num;
  CL() : num(0) {...}
CL *pCL = (CL*)malloc(sizeof(CL) * 10);

As a result, the 'num' variable won't be initialized. Of course, you can call the constructor for each object "manually", but a more correct way is to use the 'new' operator.

This is the fixed code:

CL *pCL = new CL[10];

You can look at examples of errors detected by the V630 diagnostic.

Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++, and C#

goto PVS-Studio;
We use cookies for the analysis of events to improve our content and make user interaction more convenient. By continuing the view of our web-pages you accept the terms of using these files. You can find out more about cookie-files and privacy policy or close the notification, by clicking on the button. Learn More →
Do not show