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;
public:
  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.


Bugs Found

Checked Projects
367
Collected Errors
13 552