﻿# Yes, PVS\-Studio Can Detect Memory Leaks

We are often asked if our static analyzer PVS\-Studio can detect memory leaks\. To avoid emailing the same text again and again, we decided to post a detailed answer in our blog\. Yes, PVS\-Studio can detect memory leaks and leaks of other resources\. This is achieved by means of several special diagnostics, the use of which will be demonstrated in this article\. The examples are taken from real projects\.

![0543_Memory_leaks/image1.png](https://import.viva64.com/docx/blog/0543_Memory_leaks/image1.png)

## Detecting memory and resource leaks

A [memory leak](https://en.wikipedia.org/wiki/Memory_leak) is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released\. In object\-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code\. In CWE classification, memory leaks are known as [CWE\-401](https://cwe.mitre.org/data/definitions/401.html) weaknesses\.

Memory leaks are one of the types of [resource leaks](https://en.wikipedia.org/wiki/Resource_leak)\. An example of another type of a leak is a file handle leak: it occurs when the program opens a file but doesn't close it and fails to return the file handle to the operating system\. In CWE classification, these defects are given the code [CWE\-404](https://cwe.mitre.org/data/definitions/404.html)\.

Memory and resource leaks may cause [Denial of Service](https://cwe.mitre.org/data/definitions/730.html) errors\.

Memory and resource leaks are detected by [dynamic](https://pvs-studio.com/en/blog/terms/0070/) and [static](https://pvs-studio.com/en/blog/terms/0046/) code analyzers\. Our static analyzer PVS\-Studio is one of such tools\.

PVS\-Studio uses the following diagnostics to detect these types of errors:

* [V599](https://pvs-studio.com/en/docs/warnings/v599/)\. The virtual destructor is not present, although the 'Foo' class contains virtual functions\.
* [V680](https://pvs-studio.com/en/docs/warnings/v680/)\. The 'delete A, B' expression only destroys the 'A' object\. Then the ',' operator returns a resulting value from the right side of the expression\.
* [V689](https://pvs-studio.com/en/docs/warnings/v689/)\. The destructor of the 'Foo' class is not declared as a virtual\. It is possible that a smart pointer will not destroy an object correctly\.
* [V701](https://pvs-studio.com/en/docs/warnings/v701/)\. realloc\(\) possible leak: when realloc\(\) fails in allocating memory, original pointer is lost\. Consider assigning realloc\(\) to a temporary pointer\.
* [V772](https://pvs-studio.com/en/docs/warnings/v772/)\. Calling a 'delete' operator for a void pointer will cause undefined behavior\.
* [V773](https://pvs-studio.com/en/docs/warnings/v773/)\. The function was exited without releasing the pointer/handle\. A memory/resource leak is possible\.
* [V779](https://pvs-studio.com/en/docs/warnings/v779/)\. Unreachable code detected\. It is possible that an error is present\.
* [V1002](https://pvs-studio.com/en/docs/warnings/v1002/)\. A class, containing pointers, constructor and destructor, is copied by the automatically generated operator\= or copy constructor\.
* [V1005](https://pvs-studio.com/en/docs/warnings/v1005/)\. The resource was acquired using 'X' function but was released using incompatible 'Y' function\.

## Examples

Let's take a look at several examples of memory leaks detected by PVS\-Studio in the source code of open\-source projects\.

**Example 1\.**

Project NetDefender\. PVS\-Studio diagnostic message: V773 The 'm\_pColumns' pointer was not released in destructor\. A memory leak is possible\. fireview\.cpp 95

Note that two objects are created in the constructor:

* The pointer to an object of type _CBrush_ is saved to variable _m\_pBrush\._
* The pointer to an object of type _CStringList_ is saved to variable _m\_pColumns_\.

```cpp
CFireView::CFireView() : CFormView(CFireView::IDD)
{
  m_pBrush = new CBrush;
  ASSERT(m_pBrush);
  m_clrBk = RGB(148, 210, 252);
  m_clrText = RGB(0, 0, 0);
  m_pBrush->CreateSolidBrush(m_clrBk);

  m_pColumns = new CStringList;
  ASSERT(m_pColumns);
  _rows = 1;
  start = TRUE;
  block = TRUE;
  allow = TRUE;
  ping = TRUE;
  m_style=StyleTile;
}
```

However, only one object, which address is stored in the _m\_pBrush_ variable, is destroyed in the destructor:

```cpp
CFireView::~CFireView()
{
  if(m_pBrush)
  {
     delete m_pBrush;
  }
}
```

The programmer must have simply forgotten about the _m\_pColumns_ variable, which results in a memory leak\.

**Example 2\.**

Project Far2l \(Linux port of FAR v2\)\. The interesting thing about this bug is that it triggers two different PVS\-Studio diagnostics at once:

* V779 Unreachable code detected\. It is possible that an error is present\. 7z\.cpp 203
* V773 The function was exited without releasing the 't' pointer\. A memory leak is possible\. 7z\.cpp 202

```cpp
BOOL WINAPI _export SEVENZ_OpenArchive(const char *Name,
                                       int *Type)
{
  Traverser *t = new Traverser(Name);
  if (!t->Valid())
  {
    return FALSE;
    delete t;
  }

  delete s_selected_traverser;
  s_selected_traverser = t;
  return TRUE;
}
```

The _return_ and _delete_ operator are swapped\. As a result, _delete_ will never be executed\. The analyzer issues two messages: one about unreachable code, the other about a memory leak\. 

**Example 3\.**

Project Firebird\. PVS\-Studio diagnostic message: V701 realloc\(\) possible leak: when realloc\(\) fails in allocating memory, original pointer 's\-\>base' is lost\. Consider assigning realloc\(\) to a temporary pointer\. mstring\.c 42

```cpp
int mputchar(struct mstring *s, int ch)
{
  if (!s || !s->base) return ch;
  if (s->ptr == s->end) {
    int len = s->end - s->base;
    if ((s->base = realloc(s->base, len+len+TAIL))) {
      s->ptr = s->base + len;
      s->end = s->base + len+len+TAIL; }
    else {
      s->ptr = s->end = 0;
      return ch;
    }
  }
  *s->ptr++ = ch;
  return ch;
}
```

The function in question adds a character to a string\. The buffer storing the string is extended by calling function _realloc_\. The problem here is that if _realloc_ fails to increase the buffer's size, a memory leak will occur\. This happens because when there is no available memory block large enough, the _realloc _function returns _NULL_ without releasing the previous block\. Since the calling function's return result is immediately written to variable _s\-\>base_, it is simply impossible to free the previously allocated storage\.

The bug can be fixed by adding a temporary variable and a call to function _free_:

```cpp
int mputchar(struct mstring *s, int ch)
{
  if (!s || !s->base) return ch;
  if (s->ptr == s->end) {
    void *old = s->base;
    int len = s->end - s->base;
    if ((s->base = realloc(s->base, len+len+TAIL))) {
      s->ptr = s->base + len;
      s->end = s->base + len+len+TAIL; }
    else {
      free(old);
      s->ptr = s->end = 0;
      return ch;
    }
  }
  *s->ptr++ = ch;
  return ch;
}
```

## Static and dynamic analysis

PVS\-Studio's diagnostics are a good example of how static analyzers can detect various types of resource leaks\. It should be noted, however, that static analyzers perform worse than dynamic analyzers in this field\.

Static analyzers find bugs by examining the source code and keeping track of how pointers are used, which is a very difficult task\. Pointers may be passed between functions in tricky ways, so the analyzer is not always able to follow them and notice potential memory leaks\. In some cases, it's simply impossible as the analyzer doesn't know what input data will be fed to the program\.

Detecting memory or resource leaks is much easier for dynamic analyzers because they don't have to keep track of the data\. They just need to remember the location inside the program where a resource is allocated, and check if the program has released it before exiting\. If it hasn't, then it's a bug\. So, dynamic analyzers are more careful and reliable in detecting the various types of leaks\.

This doesn't mean that dynamic analysis is more powerful than static analysis\. Both methodologies have strong and weak points of their own\. Detecting resource leaks is something that dynamic analyzers are better at\. But in other fields such as search of typos and unreachable code, they are ineffective or useless at all\.

Don't view it as "static analysis vs dynamic analysis"\. They don't compete; they complement each other\. If you want to improve your code's quality and reliability, you should use both types of analysis\. I've written a lot about it, and I don't feel like repeating myself\. For further reading, see the following articles:

* [Static and Dynamic Code Analysis](https://pvs-studio.com/en/blog/posts/0248/);
* [Myths about static analysis\. The third myth \- dynamic analysis is better than static analysis](https://pvs-studio.com/en/blog/posts/0117/);
* [Valgrind: Good but Not Enough](https://pvs-studio.com/en/blog/posts/cpp/0278/);
* [Checking the code of Valgrind dynamic analyzer by a static analyzer](https://pvs-studio.com/en/blog/posts/cpp/0504/)\.

## Conclusion

PVS\-Studio static analyzer can detect a wide range of problems caused by memory and resource leaks\. Use it regularly to have bugs eliminated as soon as they appear in your code or during night builds:

* [PVS\-Studio's incremental analysis mode](https://pvs-studio.com/en/docs/manual/0024/);
* [Direct integration of the analyzer into build automation systems \(C/C\+\+\)](https://pvs-studio.com/en/docs/manual/0006/)

The PVS\-Studio team wishes you bugless code\!