{"id":4871,"date":"2015-10-07T13:00:21","date_gmt":"2015-10-07T13:00:21","guid":{"rendered":"http:\/\/writeasync.net\/?p=4871"},"modified":"2015-10-07T05:29:01","modified_gmt":"2015-10-07T05:29:01","slug":"find-bugs-for-free","status":"publish","type":"post","link":"http:\/\/writeasync.net\/?p=4871","title":{"rendered":"Find bugs for (almost) free"},"content":{"rendered":"<p>Want to find bugs in your code for (almost) free? Try <a href=\"https:\/\/en.wikipedia.org\/wiki\/Static_program_analysis\">static code analysis<\/a> &#8212; a useful technique, though often maligned by developers for noise and <a href=\"http:\/\/codecurmudgeon.com\/wp\/2011\/11\/false-positives-and-other-misconceptions-in-static-analysis\/\">&#8220;false positives&#8221;<\/a>. If you need an <a href=\"https:\/\/en.wikipedia.org\/wiki\/Argument_from_authority\">appeal to authority<\/a> to be convinced, see how <a href=\"https:\/\/en.wikipedia.org\/wiki\/John_Carmack\">John Carmack<\/a> (of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Doom_(series)\">Doom<\/a> and <a href=\"https:\/\/en.wikipedia.org\/wiki\/Quake_(video_game)\">Quake<\/a> fame) <a href=\"http:\/\/www.gamasutra.com\/view\/news\/128836\/InDepth_Static_Code_Analysis.php\">swears by it<\/a>!<\/p>\n<p>If you use C++ and a modern version of Visual Studio, you already have a pretty powerful <a href=\"http:\/\/blogs.msdn.com\/b\/vcblog\/archive\/2015\/02\/24\/c-c-code-analysis-in-vs2015.aspx\">code analysis engine<\/a> available to you, the <code>\/analyze<\/code> compiler switch. It started life many years back as &#8220;<a href=\"http:\/\/research.microsoft.com\/en-us\/news\/features\/prefast.aspx\">PREfast<\/a>,&#8221; a technology developed and used internally at Microsoft. Over the past several years, it has been steadily improved and nicely integrated right into the Visual Studio IDE (Analyze -&gt; Run Code Analysis On Solution). Overall it is quite good at finding very common &#8212; and severe &#8212; bugs plaguing native code developers.<\/p>\n<p><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/2ayc37ac.aspx\">Null pointer dereferences?<\/a> Check.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\n#include &lt;cstdlib&gt;\r\n#include &lt;new&gt;\r\n\r\nstruct Data\r\n{\r\n    int x;\r\n};\r\n\r\nData * MallocData()\r\n{\r\n    \/\/ !!! Raises Warning C6011: Dereferencing NULL pointer 'd'.\r\n    Data* d = (Data*)malloc(sizeof(Data));\r\n    d-&gt;x = 1234;\r\n    return d;\r\n}\r\n\r\nData * NewData()\r\n{\r\n    \/\/ !!! Raises Warning C6011: Dereferencing NULL pointer. 'd' contains the same NULL value as 'new(1*4, nothrow)' did.\r\n    Data* d = new (std::nothrow) Data();\r\n    d-&gt;x = 1234;\r\n    return d;\r\n}\r\n<\/pre>\n<p><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/ms182081.aspx\">Buffer overruns?<\/a> Check.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\nwchar_t * RunOver()\r\n{\r\n    \/\/ !!! Raises Warning C6200: Index '10' is out of valid index range '0' to '9' for non-stack buffer 'buffer'.\r\n    wchar_t * buffer = new wchar_t&#x5B;10];\r\n    buffer&#x5B;10] = L'&#92;&#48;';\r\n    return buffer;\r\n}\r\n<\/pre>\n<p><a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/z5aa1ca1.aspx\">Other common data type misuses?<\/a> Check.<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\n#include &lt;Windows.h&gt;\r\n#include &lt;iostream&gt;\r\n\r\nusing namespace std;\r\n\r\nvoid Init()\r\n{\r\n    \/\/ !!! Raises Warning C6217: Implicit cast between semantically different integer types : testing HRESULT with 'not'.\r\n    \/\/     Consider using SUCCEEDED or FAILED macro instead.\r\n    if (!CoInitialize(nullptr))\r\n    {\r\n        wcerr &lt;&lt; L&quot;Failed!&quot; &lt;&lt; endl;\r\n        \/\/ ...\r\n    }\r\n    \/\/ ...\r\n}\r\n<\/pre>\n<p>It can even find race conditions if you use <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/hh916381.aspx\">concurrency annotations<\/a>:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\n#include &lt;Windows.h&gt;\r\n\r\nclass MaybeThreadSafeCounter\r\n{\r\npublic:\r\n    MaybeThreadSafeCounter()\r\n        : cs_(), count_(0)\r\n    {\r\n        InitializeCriticalSection(&amp;cs_);\r\n    }\r\n\r\n    ~MaybeThreadSafeCounter()\r\n    {\r\n        DeleteCriticalSection(&amp;cs_);\r\n    }\r\n\r\n    int Increment()\r\n    {\r\n        EnterCriticalSection(&amp;cs_);\r\n        int value = ++count_;\r\n        LeaveCriticalSection(&amp;cs_);\r\n        return value;\r\n    }\r\n\r\n    int Decrement()\r\n    {\r\n        \/\/ !!! Raises Warning C26130: Missing annotation _Requires_lock_held_(this-&gt;cs_) or _No_competing_thread_ at function\r\n        \/\/     'MaybeThreadSafeCounter::Decrement'.Otherwise it could be a race condition.\r\n        return --count_;\r\n    }\r\n\r\nprivate:\r\n    CRITICAL_SECTION cs_;\r\n    _Guarded_by_(cs_) int count_;\r\n};\r\n<\/pre>\n<p>Okay, so static analysis is not completely free. You have to run the tool and sift through the issues. In some cases you need to annotate your intent, or even clean up &#8220;harmless&#8221; coding patterns that confuse the analyzer; as Carmack says, &#8220;Anything that isn&#8217;t crystal clear to a static analysis tool probably isn&#8217;t clear to your fellow programmers, either.&#8221; For that matter, enabling and <a href=\"http:\/\/www.cprogramming.com\/tutorial\/compiler_warnings.html\">acting on compiler warnings<\/a> isn&#8217;t free either but it would be hard to find a modern day programmer who would argue against it.<\/p>\n<p>Give <code>\/analyze<\/code> a try and prepare to be shocked by what it finds lurking in your codebase.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Want to find bugs in your code for (almost) free? Try static code analysis &#8212; a useful technique, though often maligned by developers for noise and &#8220;false positives&#8221;. If you need an appeal to authority to be convinced, see how&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[101],"tags":[],"class_list":["post-4871","post","type-post","status-publish","format-standard","hentry","category-native"],"_links":{"self":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/posts\/4871","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=4871"}],"version-history":[{"count":0,"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/posts\/4871\/revisions"}],"wp:attachment":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=4871"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=4871"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=4871"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}