Featured Webinar: Simplify Compliance Workflows With New C/C++test 2024.2 & AI-Driven Automation Watch Now

Finding a Memory Leak in C or C++

Headshot of Arthur Hicken, Evangelist at Parasoft
August 2, 2023
3 min read

Due to abundant data, memory leaks in software development might be difficult to identify. This post will teach you how to use a runtime error detection program to find memory leaks in C and C++.

Memory leaks in programming software can be hard to pinpoint because there’s an abundance of data. In this article, you can learn how to find memory leaks in C and C++ applications with the help of a runtime error detection tool.

What Is a Memory Leak? C++ and C Examples

When you’re facing a memory leak, C++ and C have a set of runtime detection tools that may be able to help with performance. Those who write code in C or C++ will be familiar with memory leaks. Wikipedia offers the following definition:

In computer science, 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. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

In other words, leaks mean that dynamically-allocated memory cannot be released back to the operating system because the program no longer contains pointers that can access it. You’ve lost control of that piece of memory regardless of size and can no longer access it or free it.

One of the best examples of this behavior can be seen by running the “Hello world” program showing below.

   
/*
 * File: hello.c
 */
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char *string, *string_so_far;
    int i, length;     length = 0;
    for(i=0; i<argc; i++) {
        length += strlen(argv[i])+1;
        string = malloc(length+1);
 
        /*  * Copy the string built so far. */
        if(string_so_far != (char *)0)
            strcpy(string, string_so_far);
        else *string = '\0';
        strcat(string, argv[i]);
        if(i < argc-1) strcat(string, " ");
        string_so_far = string;
    }
    printf("You entered: %s\n", string_so_far);
    return (0);
}

If we execute this program with the following arguments:

hello this is a test

If we examine the state of the program at line 25, just before executing the call to malloc for the second time, we observe:

  • The variable string so far points to the string “hello” which was assigned as a result of the previous loop iteration.
  • The variable string points to the extended string “hello this” which was assigned on this loop iteration.

These assignments are shown schematically below; both variables point to blocks of dynamically allocated memory.

The next statement:

string_so_far = string;

will create both variables pointing to the longer memory block as shown below:

Memory leak example.

Once this happens, however, there is no remaining pointer that points to the shorter block. Even if you wanted to, there is no way that the memory that was previously pointed to by string_so_far can be reclaimed; it is now permanently allocated. This is known as a “memory leak”. C++ and C face these common issues often so it’s important to catch them early.

How Do You Find a Memory Leak in C++ and C?

While there’s no button for “detect memory leak”, C++ & c have runtime detection tools that can help. This type of error can be diagnosed by memory error detection tools, such as Parasoft Insure++. This is shown below:

[hello.c:25] **LEAK_ASSIGN**
>>         string_so_far = string;
  Memory leaked due to pointer reassignment: string
  Lost block : 0x0804bd68 thru 0x0804bd6f (8 bytes)
               string, allocated at hello.c, 15
                          malloc()  (interface)
                            main()  hello.c, 15
  Stack trace where the error occurred:
                            main()  hello.c, 25

This example is called LEAK_ASSIGN because it is caused when a pointer is re-assigned. (P.S. Other memory debuggers often don’t make a distinction between outstanding memory and actual leaked memory, but Insure++ does.) In this case, outstanding memory isn’t memory that’s awesome, it’s memory that you didn’t free, as distinct from an actual leak which is memory that you cannot free.

Types of Memory Leaks

Parasoft Insure++ can also detect several other types of leaks automatically.

Leak TypeDescription
LEAK_FREEOccurs when you free a block of memory that contains pointers to other memory blocks.
LEAK_RETURNOccurs when a function returns a pointer to an allocated block of memory, but the returned value is ignored in the calling routine.
LEAK_SCOPEOccurs when a function contains a local variable that points to a block of memory, but the function returns without saving the pointer in a global variable or passing it back to its caller.

Notice that the error message indicates the exact source line on which the problem occurs, not just where the block was allocated, which is a key issue in finding and fixing memory leaks. This is extremely important because it’s easy to introduce subtle memory leaks into your applications, but very hard to find them all.

If you’re looking for a check memory leak C++ tool,  learn more about Parasoft Insure++ here.

Runtime and Memory Error Detection and Visualization With Parasoft Insure++