Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
Yes, PVS-Studio Can Detect Memory Leaks

Yes, PVS-Studio Can Detect Memory Leaks

Nov 29 2017
Author:

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

Detecting memory and resource leaks

A 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 weaknesses.

Memory leaks are one of the types of resource leaks. 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.

Memory and resource leaks may cause Denial of Service errors.

Memory and resource leaks are detected by dynamic and static 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. The virtual destructor is not present, although the 'Foo' class contains virtual functions.
  • 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. 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. realloc() possible leak: when realloc() fails in allocating memory, original pointer is lost. Consider assigning realloc() to a temporary pointer.
  • V772. Calling a 'delete' operator for a void pointer will cause undefined behavior.
  • V773. The function was exited without releasing the pointer/handle. A memory/resource leak is possible.
  • V779. Unreachable code detected. It is possible that an error is present.
  • V1002. A class, containing pointers, constructor and destructor, is copied by the automatically generated operator= or copy constructor.
  • 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.
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:

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
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

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:

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:

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:

The PVS-Studio team wishes you bugless code!



Comments (0)

Next comments next comments
close comment form
close form

Fill out the form in 2 simple steps below:

Your contact information:

Step 1
Congratulations! This is your promo code!

Desired license type:

Step 2
Team license
Enterprise license
** By clicking this button you agree to our Privacy Policy statement
close form
Request our prices
New License
License Renewal
--Select currency--
USD
EUR
* By clicking this button you agree to our Privacy Policy statement

close form
Free PVS‑Studio license for Microsoft MVP specialists
* By clicking this button you agree to our Privacy Policy statement

close form
To get the licence for your open-source project, please fill out this form
* By clicking this button you agree to our Privacy Policy statement

close form
I am interested to try it on the platforms:
* By clicking this button you agree to our Privacy Policy statement

close form
check circle
Message submitted.

Your message has been sent. We will email you at


If you do not see the email in your inbox, please check if it is filtered to one of the following folders:

  • Promotion
  • Updates
  • Spam