V773. The function was exited without releasing the pointer/handle. A memory/resource leak is possible.


The analyzer detected a potential memory leak. This situation occurs when memory allocated by using 'malloc' or 'new' remains unreleased after use.

Consider the following example:

int *NewInt()
{
  int *p = new int;
  ....
  return p;
}

int Test()
{
  int *p = NewInt();
  int res = *p;
  return res;
}

In this code, memory allocation is put into a call to another function. Therefore, the allocated storage needs to be released accordingly after the call.

This is the fixed code, without the memory leak:

int *NewInt()
{
  int *p = new int;
  ....
  return p;
}

int Test()
{
  int *p = NewInt();
  int res = *p;
  delete p;
  return res;
}

Errors of this kind are often found in error handlers because they are generally poorly tested and treated without due care by programmers when doing code reviews. For example:

int Test()
{
  int *p = (int*)malloc(sizeof(int));
  int *q = (int*)malloc(sizeof(int));
  if (p == nullptr || q == nullptr)
  {
    std::cerr << "No memory";
    return -1;
  }
  int res = *p + *q;
  free(p);
  free(q);
  return res;
}

A situation may occur that the 'p' pointer would point to allocated memory, while 'q' would be 'nullptr'. If this happens, the allocated memory will not be released. By the way, an opposite problem is also possible: in a parallel program, you may encounter a situation when memory allocation fails on the first attempt but succeeds on the second.

Besides the memory leaks, the analyzer is able to find resource leaks: unclosed descriptors, files, etc. Such errors aren't different from each other, that's why everything said above refers to them as well. Here is a small example:

void LoadBuffer(char *buf, size_t len)
{
  FILE* f = fopen("my_file.bin", "rb");
  fread(buf, sizeof(char), len, f);
}

Note. In modern C++, it is better to avoid manual resource management and use smart pointers instead. For example, we recommend using 'std::unique_ptr': it will ensure correct memory release in all the function return points. This solution is also exception-safe.

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

You can look at examples of errors detected by the V773 diagnostic.