Search code examples
c++clinuxmemory-leakscppcheck

How to configure cppcheck to detect memory leaks in linux souce code


I want to try some open source static analysis tools to check their performance in detecting leaks on linux source code.I am starting with cppchecker. In linux most of the memory allocation calls are made through functions like kmalloc(), kzalloc() and corresponding free function is kfree(). How can I configure cppchecker to track kmalloc calls instead of default malloc() call?There is something called creating a new config file where we can define user preferences but i cant figure out how to do that.

Also as a follow up to the above question does cppcheck performs interprocedural analysis for memory leak detection? What other open source static analysis tools I can use for this purpose?


Solution

  • I am a Cppcheck developer.

    It is true that there are old builtin handling for kmalloc etc. A good start is to check the kernel with the builtin knowledge. No cfg file is needed.

    However with a cfg file you can enhance cppcheck.

    Here is a start:

    <?xml version="1.0"?>
    <def format="1">
        <memory>
            <dealloc>kfree</dealloc>
            <alloc init="false">kmalloc</alloc>
            <alloc init="true">kzalloc</alloc>
        </memory>
    </def>
    

    Save that text in a file with a name such as kernel.cfg and then use for instance --library=kernel to use that info during cppcheck analysis.

    There are lots of missing info here in this cfg. If you use --check-cfg , Cppcheck will complain when it is confused during analysis and wants more cfg-info. It mainly needs noreturn information about functions and also if a function is "leak-ignore".

    You can look in our official std.cfg file, for instance at the configuration for strcmp(). This configuration explicitly says that strcmp() is not noreturn. The configuration also has a "leak-ignore" attribute - because if you can pass a pointer to the allocated memory to strcmp() then the leaks-checker should ignore this because the strcmp() will not cause any deallocation etc.

    Let us know if you have questions about how it works.