{"id":16485,"date":"2017-08-11T10:59:03","date_gmt":"2017-08-11T17:59:03","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/vcblog\/?p=16485"},"modified":"2019-02-18T17:48:22","modified_gmt":"2019-02-18T17:48:22","slug":"c-core-guidelines-checker-in-visual-studio-2017","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cppblog\/c-core-guidelines-checker-in-visual-studio-2017\/","title":{"rendered":"C++ Core Guidelines Checker in Visual Studio 2017"},"content":{"rendered":"<p><em>This post written by Sergiy Oryekhov and Andrew Pardoe<\/em><\/p>\n<p>The <a href=\"https:\/\/github.com\/isocpp\/CppCoreGuidelines\/blob\/master\/CppCoreGuidelines.md\">C++ Core Guidelines<\/a> can help improve your code and decrease your cost of maintenance by offering a wide range of recommendations: encouraging use of the standard library, avoiding use of unsafe practices whenever possible, maintaining a consistent style, and helping you to enforce reasonable design decisions. The number of Core Guidelines recommendations may look discouraging for those who own legacy code, but even a gradual cleanup process will provide immediate improvements to your code without requiring a total rewrite.<\/p>\n<p>We&#8217;ve implemented a set of code analysis checks in Visual Studio that should help you to start moving towards safer code. We are continuing to improve these checks and add more checks specific to the C++ Core Guidelines, but the current set allows you to start today on the work of making existing code better and adopting new standards of writing modern C++.<\/p>\n<p>The C++ Core Guidelines Checker is not new: it was released as a NuGet package first, and <a href=\"https:\/\/devblogs.microsoft.com\/cppblog\/cppcorecheck\/\">it is included in Visual Studio 2017<\/a>.\u00a0 It&#8217;s built on top of the C++ code analysis tools that are included in all editions of Visual Studio. <\/p>\n<p>In Visual Studio 2017 15.3 we added more checks and fixed several bugs. We&#8217;ll provide more details about these checks in future blog posts. In this post we&#8217;ll take a quick look at how to use the tool and the kind of problems it can catch.<\/p>\n<h3>Running the C++ Core Guidelines Checker<\/h3>\n<p>The checker is a part of the <a href=\"https:\/\/docs.microsoft.com\/en-us\/visualstudio\/code-quality\/analyzing-c-cpp-code-quality-by-using-code-analysis\">C++ code analysis tools<\/a>. Let\u2019s assume we have a native C++ project. To enable code analysis, we can use the IDE:<\/p>\n<ul>\n<li>Select the project and in the context menu choose &#8216;Properties&#8217;.<\/li>\n<li>In the &#8216;Configuration Properties&#8217; tree expand the &#8216;Code Analysis&#8217; node.<\/li>\n<li>On the &#8216;General&#8217; tab check &#8216;Enable Code Analysis on Build&#8217;.<\/li>\n<\/ul>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/EnableCodeAnalysisOnBuild.png\"><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/EnableCodeAnalysisOnBuild-1024x459.png\" alt=\"Enable Code Analysis on Build\" width=\"879\" height=\"394\" class=\"alignnone size-full wp-image-16515\" \/><\/a><\/p>\n<ul>\n<li><\/span><\/span>Switch to the &#8216;Extensions&#8217; node and enable &#8216;C++ Core Check (Released)&#8217;.<\/li>\n<\/ul>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/PickCppCoreCheck.png\"><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/PickCppCoreCheck-1024x418.png\" alt=\"Select C++ Core Check (Released)\" width=\"879\" height=\"359\" class=\"alignnone size-full wp-image-16495\" \/><\/a><\/p>\n<ul>\n<li>Save properties.<\/li>\n<li>Now, each effective build of the project (when there is any change) should run code analysis with extended checks.<\/li>\n<\/ul>\n<h3>Filtering rules<\/h3>\n<p>If you are interested in viewing a subset of rules you can use rulesets to manage the warnings you will see for a project. Use the same \u2018General&#8217; tab (see &#8220;How to run C++ Core Check&#8221;) to pick an appropriate ruleset and then rebuild your project:<\/p>\n<p><a href=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/CppCoreCheckTypeRules.png\"><img decoding=\"async\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/9\/2019\/02\/CppCoreCheckTypeRules.png\" alt=\"Select C++ Core Check Type Rules\" width=\"470\" height=\"263\" class=\"alignnone size-full wp-image-16505\" \/><\/a><\/p>\n<p>You can also get more granular control over the rules by using macros in combination with <a href=\"https:\/\/docs.microsoft.com\/en-us\/cpp\/preprocessor\/warning\">#pragma warning<\/a>. For example, here&#8217;s how to enable only the type-safety rules:<\/p>\n<pre class=\"prettyprint\">\n#include &lt;CppCoreCheck\/Warnings.h&gt;\n#pragma warning(disable: ALL_CPPCORECHECK_WARNINGS)\n#pragma warning(default: CPPCORECHECK_CONST_WARNINGS)\n<\/pre>\n<p>You can also enable individual rules to make it easier to handle when code produces a lot of results:<\/p>\n<pre class=\"prettyprint\">\n#pragma warning(default: WARNING_NO_REINTERPRET_CAST)\n<\/pre>\n<h3>Problems detected by the C++ Core Guidelines Checker<\/h3>\n<p>What kind of problems can be detected by the C++ Core Guidelines Checker? Here&#8217;s a sample of rules that are available in the checker. The issues detected by these rules are usually scoped and can be fixed without large code churn. You can focus on one kind of warnings and resolve them one file at a time.<\/p>\n<p>Some of the following fixes make use of a small library of facilities, known as the <a href=\"https:\/\/github.com\/isocpp\/CppCoreGuidelines\/blob\/master\/CppCoreGuidelines.md#S-gsl\">Guidelines Support Library<\/a>, designed to support the C++ Core Guidelines. <\/p>\n<ul>\n<li>Unsafe type conversions:\n<pre class=\"prettyprint\">\n\/\/ Don't use reinterpret_cast. It is hard to maintain safely.\nauto data = reinterpret_cast&lt;char*&gt;(buffer);\n<\/pre>\n<p>The following fix can be applied here:<\/p>\n<pre class=\"prettyprint\">\n\/\/ To avoid buffer overruns use gsl::as_writeable_bytes which returns gsl::span.\nauto data = gsl::as_writeable_bytes&lt;int&gt;(gsl::make_span(buffer));\n<\/pre>\n<\/li>\n<li>Unsafe low-level resource management:\n<pre class=\"prettyprint\">\n\/\/ Avoid calling new and delete explicitly. Unique pointers are safer.\nauto buffer = new int[buffer_size];\nif (read_data(buffer, buffer_size) == read_status::insufficient_space)\n    \/\/ Likely leaking memory here unless read_data deallocates it.\n    buffer = new int[max_buffer_size];\nif (read_data(buffer, max_buffer_size) == read_status::insufficient_space)\n{\n    delete[] buffer;\n    return nullptr;\n}\n<\/pre>\n<p>To avoid problems with memory management we can rewrite this code:<\/p>\n<pre class=\"prettyprint\">\n\/\/ std::unique_pointer will own and manage this object and dispose of it\nauto buffer = std::make_unique&lt;int[]&gt;(buffer_size);\nif (read_data(buffer.get(), buffer_size) == read_status::insufficient_space)\n    buffer = std::make_unique&lt;int[]&gt;(max_buffer_size);\nif (read_data(buffer.get(), max_buffer_size) == read_status::insufficient_space)\n    return nullptr;\n<\/pre>\n<\/li>\n<li>Missing constness specifications which may lead to unexpected data modifications with later code changes:\n<pre class=\"prettyprint\">\n\/\/ If variable is assigned only once, mark it as const.\nauto buffer_size = count * sizeof(data_packet);\nauto actual_size = align(buffer_size);\nif (use_extension)\n    actual_size += extension_size;\nencrypt_bytes(buffer, actual_size);\n<\/pre>\n<p>The fix is trivial:<\/p>\n<pre class=\"prettyprint\">\n\/\/ Now buffer_size is protected from unintentional modifications.\nconst auto buffer_size = count * sizeof(data_packet);\n<\/pre>\n<\/li>\n<li>C++ Core Guidelines Checker can even detect many complex problems such as this code that is missing resource cleanup in one of the code paths. In this example the code is using a <a href=\"https:\/\/github.com\/isocpp\/CppCoreGuidelines\/blob\/master\/CppCoreGuidelines.md#SS-views\"><code>gsl::owner<\/code><\/a> type from the C++ Core Guidelines GSL.\n<pre class=\"prettyprint\">\ngsl::owner&lt;int*&gt; sequence = GetRandomSequence(); \/\/ This is not released.\ntry\n{\n    StartSimulation(sequence);\n}\ncatch (const std::exception&amp; e)\n{\n    if (KnownException(e))\n        return;                                  \/\/ Skipping resource cleanup here.\n\n    ReportException(e);\n}\ndelete [] sequence;\n<\/pre>\n<p>In this case <code>GetRandomSequence()<\/code> should be redesigned to return a smart pointer instead of <code>gsl::owner<\/code> so that it is automatically released when it goes out of scope.\n<\/li>\n<\/ul>\n<h3>In closing<\/h3>\n<p>Good tools can help you to maintain and upgrade your code. The C++ Core Guidelines are a great place to start, and the C++ Core Guidelines Checker can help you to clean up your code and keep it clean. Try out the C++ Core Guidelines Checker in Visual Studio 2017 and let us know what you think!<\/p>\n<p>If you have any feedback or suggestions for us, let us know. We can be reached via the comments below, via email (<a href=\"mailto:visualcpp@microsoft.com\">visualcpp@microsoft.com<\/a>) and you can provide feedback via <a href=\"https:\/\/docs.microsoft.com\/en-us\/visualstudio\/ide\/how-to-report-a-problem-with-visual-studio-2017\">Help &gt; Report A Problem in the product<\/a>, or via <a href=\"https:\/\/developercommunity.visualstudio.com\/topics\/C%2B%2B.html\">Developer Community<\/a>. You can also find us on Twitter (<a href=\"https:\/\/twitter.com\/visualc\">@VisualC<\/a>) and Facebook (<a href=\"https:\/\/www.facebook.com\/msftvisualcpp\">msftvisualcpp<\/a>).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This post written by Sergiy Oryekhov and Andrew Pardoe The C++ Core Guidelines can help improve your code and decrease your cost of maintenance by offering a wide range of recommendations: encouraging use of the standard library, avoiding use of unsafe practices whenever possible, maintaining a consistent style, and helping you to enforce reasonable design [&hellip;]<\/p>\n","protected":false},"author":312,"featured_media":35994,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[245],"class_list":["post-16485","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cplusplus","tag-cppcorecheck"],"acf":[],"blog_post_summary":"<p>This post written by Sergiy Oryekhov and Andrew Pardoe The C++ Core Guidelines can help improve your code and decrease your cost of maintenance by offering a wide range of recommendations: encouraging use of the standard library, avoiding use of unsafe practices whenever possible, maintaining a consistent style, and helping you to enforce reasonable design [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/16485","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/users\/312"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/comments?post=16485"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/posts\/16485\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media\/35994"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/media?parent=16485"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/categories?post=16485"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cppblog\/wp-json\/wp\/v2\/tags?post=16485"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}