{"id":5357,"date":"2017-12-08T12:54:26","date_gmt":"2017-12-08T12:54:26","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-allocating-and-deallocating\/"},"modified":"2023-06-26T12:00:51","modified_gmt":"2023-06-26T12:00:51","slug":"c-core-guidelines-allocating-and-deallocating","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-allocating-and-deallocating\/","title":{"rendered":"C++ Core Guidelines: Rules for Allocating and Deallocating"},"content":{"rendered":"<p>The guidelines have six rules for explicit memory allocation and deallocation. Six! Maybe you are surprised because there is a simple rule in modern C++: don&#8217;t use new and delete. The story is not so simple.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5353\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/German_Monopoly_board_in_the_middle_of_a_game.png\" alt=\"German Monopoly board in the middle of a game\" width=\"600\" height=\"370\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/German_Monopoly_board_in_the_middle_of_a_game.png 881w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/German_Monopoly_board_in_the_middle_of_a_game-300x185.png 300w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/German_Monopoly_board_in_the_middle_of_a_game-768x474.png 768w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>Here are the six rules.<\/p>\n<ul>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-mallocfree\">R.10: Avoid <code class=\"highlighter-rouge no-highlight\">malloc()<\/code> and <code class=\"highlighter-rouge no-highlight\">free()<\/code><\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-newdelete\">R.11: Avoid calling <code class=\"highlighter-rouge no-highlight\">new<\/code> and <code class=\"highlighter-rouge no-highlight\">delete<\/code> explicitly<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-immediate-alloc\">R.12: Immediately give the result of an explicit resource allocation to a manager object<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-single-alloc\">R.13: Perform at most one explicit resource allocation in a single expression statement<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-ap\">R.14: ??? array vs. pointer parameter<\/a><\/li>\n<li><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-pair\">R.15: Always overload matched allocation\/deallocation pairs<\/a><\/li>\n<\/ul>\n<p>I will not write about the last two rules. First, rule R.14 is not baked enough, and second, rule R.15 is quite special. If you want to learn more about overloading <span style=\"font-family: courier new,courier;\">new<\/span> and <span style=\"font-family: courier new,courier;\">delete,<\/span> you should read my posts on <a href=\"https:\/\/www.modernescpp.com\/index.php\/tag\/new-delete\">memory allocation and deallocation<\/a>.<\/p>\n<p>Before I dive into the rules, let me give you a little background necessary for understanding the rules. Creating an object in C++ with <span style=\"font-family: courier new,courier;\">new<\/span> consists of two steps.<\/p>\n<ol>\n<li>Allocate the memory for the object<\/li>\n<li>Constructing the object into the allocated memory<\/li>\n<\/ol>\n<p><a href=\"http:\/\/en.cppreference.com\/w\/cpp\/memory\/new\/operator_new\"><span style=\"font-family: courier new,courier;\">operator new<\/span> or <span style=\"font-family: courier new,courier;\">operator new []<\/span><\/a> makes the first step; the constructor the second step.<\/p>\n<p>The same strategy applies to the destruction but the other way around. First, the destructor is called (if any), and then the memory is deallocated with <a href=\"http:\/\/en.cppreference.com\/w\/cpp\/memory\/new\/operator_delete\"><span style=\"font-family: courier new,courier;\">operator delete<\/span> or <span style=\"font-family: courier new,courier;\">operator delete []<\/span><\/a>. This two-step creation and destruction is the reason for the four rules. So, let&#8217;s start.<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-mallocfree\">R.10: Avoid <code class=\"highlighter-rouge no-highlight\">malloc()<\/code> and <code class=\"highlighter-rouge no-highlight\">free()<\/code><\/a><\/h3>\n<p>What is the difference between <span style=\"font-family: courier new,courier;\">new<\/span> and <span style=\"font-family: courier new,courier;\">malloc<\/span>, or<span style=\"font-family: courier new,courier;\"> delete<\/span> and <span style=\"font-family: courier new,courier;\">free<\/span>? The C-functions <span style=\"font-family: courier new,courier;\">malloc<\/span> and <span style=\"font-family: courier new,courier;\">free<\/span> do only half of the job. <span style=\"font-family: courier new,courier;\">malloc<\/span> allocates the memory and <span style=\"font-family: courier new,courier;\">free<\/span> only deallocates the memory. Neither does <span style=\"font-family: courier new,courier;\">malloc<\/span> invoke the constructor, nor does free invoke the destructor.<\/p>\n<p>This means if you use an object which was just <em>created<\/em> via <span style=\"font-family: courier new,courier;\">malloc,<\/span> you will get undefined behavior.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #0099ff; font-style: italic;\">\/\/ mallocVersusNew.cpp<\/span>\r\n\r\n<span style=\"color: #009999;\">#include &lt;iostream&gt;<\/span>\r\n<span style=\"color: #009999;\">#include &lt;string&gt;<\/span>\r\n\r\n<span style=\"color: #006699; font-weight: bold;\">struct<\/span> Record{\r\n  Record(std<span style=\"color: #555555;\">::<\/span>string na <span style=\"color: #555555;\">=<\/span> <span style=\"color: #cc3300;\">\"Record\"<\/span>)<span style=\"color: #555555;\">:<\/span> name(na){}                 <span style=\"color: #0099ff; font-style: italic;\">\/\/ (4)<\/span>\r\n  std<span style=\"color: #555555;\">::<\/span>string name;\r\n};\r\n\r\n<span style=\"color: #007788; font-weight: bold;\">int<\/span> <span style=\"color: #cc00ff;\">main<\/span>(){\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n    \r\n    Record<span style=\"color: #555555;\">*<\/span> p1 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">static_cast<\/span><span style=\"color: #555555;\">&lt;<\/span>Record<span style=\"color: #555555;\">*&gt;<\/span>(malloc(<span style=\"color: #006699; font-weight: bold;\">sizeof<\/span>(Record)));  <span style=\"color: #0099ff; font-style: italic;\">\/\/ (1)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> p1<span style=\"color: #555555;\">-&gt;<\/span>name <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;                         <span style=\"color: #0099ff; font-style: italic;\">\/\/ (3)<\/span>\r\n\r\n    <span style=\"color: #006699; font-weight: bold;\">auto<\/span> p2 <span style=\"color: #555555;\">=<\/span> <span style=\"color: #006699; font-weight: bold;\">new<\/span> Record;                                       <span style=\"color: #0099ff; font-style: italic;\">\/\/ (2)<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> p2<span style=\"color: #555555;\">-&gt;<\/span>name <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;                         <span style=\"color: #0099ff; font-style: italic;\">  <\/span>\r\n    \r\n    std<span style=\"color: #555555;\">::<\/span>cout <span style=\"color: #555555;\">&lt;&lt;<\/span> std<span style=\"color: #555555;\">::<\/span>endl;\r\n   \r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>I only allocate in (1) memory for my <span style=\"font-family: courier new,courier;\">Record<\/span> object. The result is that the output <span style=\"font-family: courier new,courier;\">p1-&gt;name<\/span> in (3) is undefined behavior. In contrast, call (2) invokes the constructor in line (4). Undefined behavior means that you can not make any assumptions about the program&#8217;s output.<\/p>\n<p>Depending on the used platform and the used GCC, the result of the program is entirely different.<\/p>\n<ul>\n<li>GCC 4.8.5 produces a core dump on my local PC<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5354\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/mallocVersusNewGcc.png\" alt=\"mallocVersusNewGcc\" width=\"563\" height=\"187\" style=\"display: block; margin-left: auto; margin-right: auto;\" srcset=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/mallocVersusNewGcc.png 563w, https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/mallocVersusNewGcc-300x100.png 300w\" sizes=\"auto, (max-width: 563px) 100vw, 563px\" \/><\/p>\n<ul>\n<li>GCC 4.9 (on cppreference.com) produces no output<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5355\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/mallocVersusNewOnline49.png\" alt=\"mallocVersusNewOnline49\" width=\"240\" height=\"87\" style=\"display: block; margin-left: auto; margin-right: auto;\" \/><\/p>\n<ul>\n<li>GCC 7.1 (cppreference.com) produces the <em>expected<\/em> output<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\" size-full wp-image-5356\" src=\"https:\/\/www.modernescpp.com\/wp-content\/uploads\/2017\/12\/mallocVersusNewOnline71.png\" alt=\"mallocVersusNewOnline71\" style=\"display: block; margin-left: auto; margin-right: auto;\" width=\"291\" height=\"145\" \/><\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-newdelete\">R.11: Avoid calling <code class=\"highlighter-rouge no-highlight\">new<\/code> and <code class=\"highlighter-rouge no-highlight\">delete<\/code> explicitly<\/a><\/h3>\n<p>You should keep this rule in mind. The emphasis in this rule lies on the word <strong>explicitly<\/strong> because using smart pointers or containers of the Standard Template Library gives you the object which use <strong>implicitly<\/strong> <span style=\"font-family: courier new,courier;\">new<\/span> and <span style=\"font-family: courier new,courier;\">delete.<\/span><\/p>\n<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-immediate-alloc\">R.12: Immediately give the result of an explicit resource allocation to a manager object<\/a><\/h3>\n<p>This is the key idea of a smart pointer such as <span style=\"font-family: courier new,courier;\">std::unique_ptr&lt;int&gt; upInt(new int()) and<\/span> will not hold in the counterexample from the guidelines. If the allocation of the buffer fails, the file handle will be lost.<\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">f<\/span>(<span style=\"color: #006699; font-weight: bold;\">const<\/span> std<span style=\"color: #555555;\">::<\/span>string<span style=\"color: #555555;\">&amp;<\/span> name)\r\n{\r\n    <span style=\"color: #007788; font-weight: bold;\">FILE<\/span><span style=\"color: #555555;\">*<\/span> f <span style=\"color: #555555;\">=<\/span> fopen(name, <span style=\"color: #cc3300;\">\"r\"<\/span>);            <span style=\"color: #0099ff; font-style: italic;\">\/\/ open the file<\/span>\r\n    std<span style=\"color: #555555;\">::<\/span>vector<span style=\"color: #555555;\">&lt;<\/span><span style=\"color: #007788; font-weight: bold;\">char<\/span><span style=\"color: #555555;\">&gt;<\/span> buf(<span style=\"color: #ff6600;\">1024<\/span>);\r\n    fclose(f);                             <span style=\"color: #0099ff; font-style: italic;\">\/\/ close the file<\/span>\r\n}\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<h3><a href=\"http:\/\/isocpp.github.io\/CppCoreGuidelines\/CppCoreGuidelines#Rr-single-alloc\">R.13: Perform at most one explicit resource allocation in a single expression statement<\/a><\/h3>\n<p>This rule is a little bit tricky. <span style=\"font-family: courier new,courier;\"><br \/><\/span><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #007788; font-weight: bold;\">void<\/span> <span style=\"color: #cc00ff;\">func<\/span>(std<span style=\"color: #555555;\">::<\/span>shared_ptr<span style=\"color: #555555;\">&lt;<\/span>Widget<span style=\"color: #555555;\">&gt;<\/span> sp1, std<span style=\"color: #555555;\">::<\/span>shared_ptr<span style=\"color: #555555;\">&lt;<\/span>Widget<span style=\"color: #555555;\">&gt;<\/span> sp2){\r\n ...\r\n}\r\n\r\nfunc(std<span style=\"color: #555555;\">::<\/span>shared_ptr<span style=\"color: #555555;\">&lt;<\/span>Widget<span style=\"color: #555555;\">&gt;<\/span>(<span style=\"color: #006699; font-weight: bold;\">new<\/span> Widget(1)), std<span style=\"color: #555555;\">::<\/span>shared_ptr<span style=\"color: #555555;\">&lt;<\/span>Widget<span style=\"color: #555555;\">&gt;<\/span>(<span style=\"color: #006699; font-weight: bold;\">new<\/span> Widget(2)));\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>This function call is not exception-safe and may result in a memory leak. Why? The reason is that four operations must be performed to initialize the shared pointers.<\/p>\n<ol>\n<li>Allocate memory for <span style=\"font-family: courier new,courier;\">Widget(1)<\/span><\/li>\n<li>Construct <span style=\"font-family: courier new,courier;\">Widget(1)<\/span><\/li>\n<li>Allocate memory for <span style=\"font-family: courier new,courier;\">Widget(2)<\/span><\/li>\n<li>Construct <span style=\"font-family: courier new,courier;\">Widget(2)<\/span><\/li>\n<\/ol>\n<p>The compiler can allocate the memory for <span style=\"font-family: courier new,courier;\">Widget(1)<\/span> and <span style=\"font-family: courier new,courier;\">Widget(2)<\/span> and then construct both.<\/p>\n<ol>\n<li>Allocate memory for <span style=\"font-family: courier new,courier;\">Widget(1)<\/span><\/li>\n<li>Allocate memory for <span style=\"font-family: courier new,courier;\">Widget(2)<\/span><\/li>\n<li>Construct <span style=\"font-family: courier new,courier;\">Widget(1)<\/span><\/li>\n<li>Construct <span style=\"font-family: courier new,courier;\">Widget(2)<\/span><\/li>\n<\/ol>\n<p>If one of the constructors throws an exception, the memory of the other object will not be automatically freed, and we will get a memory leak.<\/p>\n<p>It&#8217;s easy to overcome this issue using the factory function std::make_shared to create a<span style=\"font-family: courier new,courier;\"> std::shared_ptr. <\/span>&nbsp; <span style=\"font-family: courier new,courier;\"><br \/><\/span><\/p>\n<div style=\"background: #f0f3f3; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\">func(std<span style=\"color: #555555;\">::<\/span>make_shared<span style=\"color: #555555;\">&lt;<\/span>Widget<span style=\"color: #555555;\">&gt;<\/span>(<span style=\"color: #ff6600;\">1<\/span>), std<span style=\"color: #555555;\">::<\/span>make_shared<span style=\"color: #555555;\">&lt;<\/span>Widget<span style=\"color: #555555;\">&gt;<\/span>(<span style=\"color: #ff6600;\">2<\/span>));\r\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p><span style=\"font-family: courier new,courier;\">std::make_shared<\/span> guarantees that the function will have no effect if an exception is thrown. The pendant function <span style=\"font-family: courier new,courier;\">std::make_unique<\/span> for creating a <span style=\"font-family: courier new,courier;\">std::unique_ptr<\/span> guarantees the same.&nbsp;<\/p>\n<h2>What&#8217;s next?<\/h2>\n<p>The next rules to resource management will follow Rule R.11: avoid calling <span style=\"font-family: courier new,courier;\">new<\/span> and <span style=\"font-family: courier new,courier;\">delete<\/span> explicitly; therefore, the <a href=\"https:\/\/www.modernescpp.com\/index.php\/c-core-guidelines-rules-to-smart-pointers\">next post<\/a> will be about the smart pointers <span style=\"font-family: courier new,courier;\">std::unique_ptr<\/span>, <span style=\"font-family: courier new,courier;\">std::shared_ptr<\/span>, and <span style=\"font-family: courier new,courier;\">std::weak_ptr<\/span>.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The guidelines have six rules for explicit memory allocation and deallocation. Six! Maybe you are surprised because there is a simple rule in modern C++: don&#8217;t use new and delete. The story is not so simple.<\/p>\n","protected":false},"author":21,"featured_media":5353,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[372],"tags":[498],"class_list":["post-5357","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-modern-c","tag-memory"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5357","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/comments?post=5357"}],"version-history":[{"count":1,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5357\/revisions"}],"predecessor-version":[{"id":6848,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5357\/revisions\/6848"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/5353"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5357"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5357"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5357"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}