Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3584

Dynamically allocated memory should be released

    XMLWordPrintable

    Details

    • Message:
      Review the data-flow; this memory allocation might not have been released when reaching exit point at line {{line}}.
    • Highlighting:
      • Primary: the allocation call - [m|c|re]alloc|new
      • Additional: statement exiting the function
        • Message: Exit point
    • Default Severity:
      Blocker
    • Impact:
      High
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C, C++, Objective-C
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • CERT:
      MEM31-C.
    • CWE:
      CWE-401

      Description

      Memory allocated dynamically with calloc(...), malloc(...), realloc(...) or new should be released when it's not needed anymore. Failure to do so will result in a memory leak that could bring the box to its knees.

      This rule raises an issue when memory is allocated and not freed in the same function. Allocated memory is ignored if a pointer to it is {{return}}ed to the caller or stored in a structure that's external to the function.

      Noncompliant Code Example

      int fun() {
        char* name = (char *) malloc (size);
        if (!name) {
          return 1;
        }
        // ...
        return 0; // Noncompliant, memory pointed by "name" has not been released
      }
      

      Compliant Solution

      int fun() {
        char* name = (char *) malloc (size);
        if (!name) {
          return 1;
        }
        // ...
        free(name);
        return 0;
      }
      

      See

      • MITRE, CWE-401 - Improper Release of Memory Before Removing Last Reference ('Memory Leak')
      • MEM00-C. - Allocate and free memory in the same module, at the same level of abstraction
      • CERT, MEM31-C. - Free dynamically allocated memory when no longer needed

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              massimo.paladin Massimo PALADIN
              Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: