Menu

False negative: memleak is missed when main uses a trailing return type

Rodri
2026-07-28
2026-07-28
  • Rodri

    Rodri - 2026-07-28

    Hi, I found a false negative regarding the rule memleak.

    In the following C++ program, cppcheck should report a memleak warning because memory allocated by malloc is never released. However, cppcheck reports no such warning.

    #include <stdlib.h>
    
    auto main() -> int {
      int result = 0;
      auto a = static_cast<char *>(malloc(10));
      if (a) {
        a[0] = 0;
        result = a[0];
      }
      return result;
    }
    

    If malloc(10) succeeds, a is returned from main without being passed to free(a), so the allocation is leaked.

    The false negative is caused by the trailing return type form of main, not by the static_cast. With int main(), cppcheck reports the leak even when the allocation is written as auto a = static_cast<char *>(malloc(10));. With auto main() -> int, cppcheck misses the leak.

    Actual result

    Cppcheck reports no memleak warning for the program.

    Expected result

    Cppcheck should report memleak for a.

    Verification

    The issue was reproduced with:

    cppcheck --output-format=xmlv2 --enable=all memleak_trailing_return_main.cpp
    

    Version: 2.21.0

     
  • CHR

    CHR - 2026-07-28

    With head:

    test.cpp:8:3: error: Memory leak: a [memleak]
      return result;
      ^
    
     
  • Rodri

    Rodri - 2026-07-28

    Thanks for checking. My report was based on cppcheck 2.21.0. Since HEAD reports the memleak warning correctly, this appears to have already been fixed.

     

Log in to post a comment.