V586. The 'Foo' function is called twice for deallocation of the same resource.


Analyzer detected a potential error of recurrent resource deallocation. Under certain circumstances this code may turn into a security defect. The resource mentioned could be a memory space, some file or, for example, an HBRUSH object.

Let's review the example of incorrect code:

float *p1 = (float *)malloc(N * sizeof(float));
float *p2 = (float *)malloc(K * sizeof(float));
...
free(p1);
free(p1);

There is a misprint in application's source code which causes the double deallocation of same memory space. It is hard to predict the consequences of such code's execution. It's possible that such a program would crash. Or it will continue its execution but memory leak will occur.

Moreover, this code is a security defect and may lead to a vulnerability. For example, the 'malloc' ('dmalloc') function by Doug Lea that is used in some libraries as 'malloc' by default, is subject to the vulnerability. There are several conditions needed for the appearance of the vulnerability, related to the double memory freeing: memory blocks, contiguously-allocated with the freed ones, should not be free, and the list of the free memory blocks should be empty. In this case it is possible to create an exploit. Despite the fact that vulnerabilities of this kind are hard to exploit because of its specific memory configuration, there are real examples of the vulnerable code that was successfully hacked.

The correct example:

float *p1 = (float *)malloc(N * sizeof(float));
float *p2 = (float *)malloc(K * sizeof(float));
...
free(p1);
free(p2);

Sometimes an error of double resource deallocation is not a dangerous one:

vector<unsigned> m_arrStack;
...
m_arrStack.clear();
m_arrBlock.clear();
m_arrStack.clear();

Accidently the array is emptied twice. The code operates correctly but still it should be reviewed and corrected. During its study, it could be discovered that another array dissaalocation should have been performed nevertheless.

The correct example:

vector<unsigned> m_arrStack;
...
m_arrStack.clear();
m_arrBlock.clear();

According to Common Weakness Enumeration, potential errors found by using this diagnostic are classified as CWE-415, CWE-675.

You can look at examples of errors detected by the V586 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