Skip to main content
Engineering LibreTexts

6.2: Memory leaks

  • Page ID
    40740
  • There is one more memory error that may or may not deserve a paddling. If you allocate a chunk of memory and never free it, that’s a “memory leak”.

    For some programs, memory leaks are ok. For example, if your program allocates memory, performs computations on it, and then exits, it is probably not necessary to free the allocated memory. When the program exits, all of its memory is deallocated by the operating system. Freeing memory immediately before exiting might feel more responsible, but it is mostly a waste of time.

    But if a program runs for a long time and leaks memory, its total memory use will increase indefinitely. At that point, a few things might happen:

    • At some point, the system runs out of physical memory. On systems without virtual memory, the next call to malloc will fail, returning NULL.
    • On systems with virtual memory, the operating system can move another process’s pages from memory to disk and then allocate more space to the leaking process. I explain this mechanism in Section 7.8.
    • There might be a limit on the amount of space a single process can allocate; beyond that, malloc returns NULL.
    • Eventually, a process might fill its virtual address space (or the usable part). After that, there are no more addresses to allocate, so malloc returns NULL.

    If malloc returns NULL, but you persist and access the chunk you think you allocated, you get a segmentation fault. For this reason, it is considered good style to check the result from malloc before using it. One option is to add a condition like this after every malloc call:

    void *p = malloc(size);
    if (p == NULL) {
        perror("malloc failed");
        exit(-1);
    }
    

    perror is declared in stdio.h; it prints an error message and additional information about the last error that occurred.

    exit, which is declared in stdlib.h, causes the process to terminate. The argument is a status code that indicates how the process terminated. By convention, status code 0 indicates normal termination and -1 indicates an error condition. Sometimes other codes are used to indicate different error conditions.

    Error-checking code can be a nuisance, and it makes programs harder to read. You can mitigate these problems by wrapping library function calls and their error-checking code in your own functions. For example, here is a malloc wrapper that checks the return value.

    void *check_malloc(int size)
    {
        void *p = malloc (size);
        if (p == NULL) {
            perror("malloc failed");
            exit(-1);
        }
        return p;
    }
    

    Because memory management is so difficult, most large programs, like web browsers, leak memory. To see which programs on your system are using the most memory, you can use the UNIX utilities ps and top.

    • Was this article helpful?