To get a trial key
fill out the form below
Team License (a basic version)
Enterprise License (an extended version)
* By clicking this button you agree to our Privacy Policy statement

Request our prices
New License
License Renewal
--Select currency--
USD
EUR
GBP
RUB
* By clicking this button you agree to our Privacy Policy statement

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

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

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

Message submitted.

Your message has been sent. We will email you at


If you haven't received our response, please do the following:
check your Spam/Junk folder and click the "Not Spam" button for our message.
This way, you won't miss messages from our team in the future.

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

Popular related articles
Technologies used in the PVS-Studio code analyzer for finding bugs and potential vulnerabilities

Date: Nov 21 2018

Author: Andrey Karpov

A brief description of technologies used in the PVS-Studio tool, which let us effectively detect a large number of error patterns and potential vulnerabilities. The article describes the implementati…
The way static analyzers fight against false positives, and why they do it

Date: Mar 20 2017

Author: Andrey Karpov

In my previous article I wrote that I don't like the approach of evaluating the efficiency of static analyzers with the help of synthetic tests. In that article, I give the example of a code fragment…
Static analysis as part of the development process in Unreal Engine

Date: Jun 27 2017

Author: Andrey Karpov

Unreal Engine continues to develop as new code is added and previously written code is changed. What is the inevitable consequence of ongoing development in a project? The emergence of new bugs in th…
Free PVS-Studio for those who develops open source projects

Date: Dec 22 2018

Author: Andrey Karpov

On the New 2019 year's eve, a PVS-Studio team decided to make a nice gift for all contributors of open-source projects hosted on GitHub, GitLab or Bitbucket. They are given free usage of PVS-Studio s…
The Ultimate Question of Programming, Refactoring, and Everything

Date: Apr 14 2016

Author: Andrey Karpov

Yes, you've guessed correctly - the answer is "42". In this article you will find 42 recommendations about coding in C++ that can help a programmer avoid a lot of errors, save time and effort. The au…
The Evil within the Comparison Functions

Date: May 19 2017

Author: Andrey Karpov

Perhaps, readers remember my article titled "Last line effect". It describes a pattern I've once noticed: in most cases programmers make an error in the last line of similar text blocks. Now I want t…
Appreciate Static Code Analysis!

Date: Oct 16 2017

Author: Andrey Karpov

I am really astonished by the capabilities of static code analysis even though I am one of the developers of PVS-Studio analyzer myself. The tool surprised me the other day as it turned out to be sma…
PVS-Studio for Java

Date: Jan 17 2019

Author: Andrey Karpov

In the seventh version of the PVS-Studio static analyzer, we added support of the Java language. It's time for a brief story of how we've started making support of the Java language, how far we've co…
The Last Line Effect

Date: May 31 2014

Author: Andrey Karpov

I have studied many errors caused by the use of the Copy-Paste method, and can assure you that programmers most often tend to make mistakes in the last fragment of a homogeneous code block. I have ne…
PVS-Studio ROI

Date: Jan 30 2019

Author: Andrey Karpov

Occasionally, we're asked a question, what monetary value the company will receive from using PVS-Studio. We decided to draw up a response in the form of an article and provide tables, which will sho…

Comments (0)

Next comments
This website uses cookies and other technology to provide you a more personalized experience. By continuing the view of our web-pages you accept the terms of using these files. If you don't want your personal data to be processed, please, leave this site.
Learn More →
Accept