{"id":5104,"date":"2016-12-29T06:06:34","date_gmt":"2016-12-29T06:06:34","guid":{"rendered":"https:\/\/www.modernescpp.com\/index.php\/explicit-memory-management\/"},"modified":"2023-09-18T15:47:01","modified_gmt":"2023-09-18T15:47:01","slug":"explicit-memory-management","status":"publish","type":"post","link":"https:\/\/www.modernescpp.com\/index.php\/explicit-memory-management\/","title":{"rendered":"Explicit Memory Management"},"content":{"rendered":"<p>Explicit memory management has in C++ a high complexity but also provides great functionality. Sadly, this special domain is not so known in C++. For example, you can directly create objects in static memory, in a reserved area, or even a memory pool. That is functionality, which is often key in safety-critical applications in the embedded world. Before the harvest is the work, therefore, I will give in this post an overview, before I dive deeper into the details.<\/p>\n<p><!--more--><\/p>\n<p>&nbsp;<\/p>\n<p>In C++, we use <span style=\"font-family: courier new,courier;\">new<\/span> and <span style=\"font-family: courier new,courier;\">new[]<\/span> for memory allocation and <span style=\"font-family: courier new,courier;\">delete<\/span> and <span style=\"font-family: courier new,courier;\">delete[]<\/span> for memory deallocation. But that is by far not the whole story.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Memory_allocation\"><\/span>Memory allocation<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"new\"><\/span>new<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Thanks to the <span style=\"font-family: courier new,courier;\">operator new<\/span>, you can dynamically allocate memory for the instance of a type.<span style=\"font-family: courier new,courier;\"><\/span><\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #2b91af;\">int<\/span>* i= <span style=\"color: #0000ff;\">new<\/span> <span style=\"color: #2b91af;\">int<\/span>;\n<span style=\"color: #2b91af;\">double<\/span>* x= <span style=\"color: #0000ff;\">new<\/span> <span style=\"color: #2b91af;\">double<\/span>(10.0);\nCircle* c= <span style=\"color: #0000ff;\">new<\/span> Circle;\nPoint* p= <span style=\"color: #0000ff;\">new<\/span> Point(1.0, 2.0);\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The in parentheses used arguments are the arguments for the constructor. The result of the <span style=\"font-family: courier new,courier;\">new<\/span> call is a pointer to the according to type. The initialization of the instance is happing after the allocation of the memory. <span>Placement new<\/span> uses the fact that <span style=\"font-family: courier new,courier;\">new<\/span> consists of two steps. If the object is an object of a class hierarchy, the constructors of all base classes will automatically be performed.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"new-2\"><\/span>new[]<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p><span style=\"font-family: courier new,courier;\">new[]<\/span> creates in opposite to <span style=\"font-family: courier new,courier;\">new a<\/span> C array of objects. The newly created objects need a default constructor.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #2b91af;\">double<\/span>* da= <span style=\"color: #0000ff;\">new<\/span> <span style=\"color: #2b91af;\">double<\/span>[5];\nCircle* ca= <span style=\"color: #0000ff;\">new<\/span> Circle[8];\n<\/pre>\n<\/div>\n<h3><span class=\"ez-toc-section\" id=\"Placement_new\"><\/span>Placement new<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>Placement new is often used to instantiate an object in a pre-reserved memory area. In addition, you can overload placement new globally and for your own data types. This is a big benefit that C++ offers.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<table>\n<tbody>\n<tr>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\">1\n2\n3\n4\n5<\/pre>\n<\/td>\n<td>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #2b91af;\">char<\/span>* memory= <span style=\"color: #0000ff;\">new<\/span> <span style=\"color: #2b91af;\">char<\/span>[<span style=\"color: #0000ff;\">sizeof<\/span>(Account)];\nAccount* a= <span style=\"color: #0000ff;\">new<\/span>(memory) Account;\n\n<span style=\"color: #2b91af;\">char<\/span>* memory2= <span style=\"color: #0000ff;\">new<\/span> <span style=\"color: #2b91af;\">char<\/span>[5*<span style=\"color: #0000ff;\">sizeof<\/span>(Account)];\nAccount* b= <span style=\"color: #0000ff;\">new<\/span>(memory2) Account[5];\n<\/pre>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Placement new needs an additional argument (lines 2 and 5). Lines 1 and 4 are why the <span><\/span><span style=\"font-family: courier new,courier;\"><span>operator<\/span> new(sizeof(Account),memory) <\/span>can be used. Or to say it the other way around. The object will be instantiated in the memory area<span style=\"font-family: courier new,courier;\"> <\/span><span style=\"font-family: courier new,courier;\">memory<\/span>. Accordingly, the same holds for the C array<span style=\"font-family: courier new,courier;\"> b<\/span>.<span style=\"font-family: courier new,courier;\"><\/span><\/p>\n<h3><span class=\"ez-toc-section\" id=\"Failed_allocation\"><\/span>Failed allocation<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>If the memory allocations fail <span style=\"font-family: courier new,courier;\">new<\/span> and<span style=\"font-family: courier new,courier;\"> new[]<\/span> will raise a <span style=\"font-family: courier new,courier;\">std::bad_alloc<\/span> exception. But that is often not the behavior you want. Therefore, you can invoke placement new with a constant <span style=\"font-family: courier new,courier;\">std::nothrow:<\/span> <span style=\"font-family: courier new,courier;\">char* c new(std::nothrow) char[10].<\/span> This call causes you will get a <span style=\"font-family: courier new,courier;\">nullptr<\/span> in the error case.<\/p>\n<h4>New handler<\/h4>\n<p>In the case of a failed allocation, you can use <span style=\"font-family: courier new,courier;\">std::set_new_handler<\/span> as your own handler. <span style=\"font-family: courier new,courier;\">std::set_new_handler<\/span> returns the older handler and needs a callable unit. This callable unit should take no argument and return nothing. You can get the currently used handler by invoking the function <span style=\"font-family: courier new,courier;\">std::get_new_handler.<\/span><\/p>\n<p>Your handler allows you to implement special strategies for failed allocations:<\/p>\n<ul>\n<li>request more memory<\/li>\n<li>terminate the program with <span style=\"font-family: courier new,courier;\">std::terminate<\/span><\/li>\n<li>throw an exception of type <span style=\"font-family: courier new,courier;\">std::bad_alloc<\/span><\/li>\n<\/ul>\n<h2><span class=\"ez-toc-section\" id=\"Memory_deallocation\"><\/span>Memory deallocation<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<h3><span class=\"ez-toc-section\" id=\"delete\"><\/span>delete<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>A with <span style=\"font-family: courier new,courier;\">new<\/span> previously allocated memory will be deallocated with <span style=\"font-family: courier new,courier;\">delete.<\/span><\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\">Circle* c= <span style=\"color: #0000ff;\">new<\/span> Circle;\n...\n<span style=\"color: #0000ff;\">delete<\/span> c;\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>The object&#8217;s destructors and base classes&#8217; destructors will automatically be called. If the base class&#8217;s destructor is virtual, you can destroy the object with a pointer or reference to the base class.<\/p>\n<p>After the object&#8217;s memory is deallocated, access to the object is undefined. You can point the pointer of the object to a different object.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"delete-2\"><\/span>delete[]<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>You have to use the operator <span style=\"font-family: courier new,courier;\">delete[]<\/span> to deallocate a C array that was allocated with <span style=\"font-family: courier new,courier;\">new[].<\/span><\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\">Circle* ca= <span style=\"color: #0000ff;\">new<\/span> Circle[8];\n...\n<span style=\"color: #0000ff;\">delete<\/span>[] ca;\n<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p>By invoking <span style=\"font-family: courier new,courier;\">delete[]<\/span> all destructors of the objects will automatically be invoked.<\/p>\n<p>The deallocation of a C array with <span style=\"font-family: courier new,courier;\">delete<\/span> is undefined behavior.<\/p>\n<h3><span class=\"ez-toc-section\" id=\"Placement_delete\"><\/span>Placement delete<span class=\"ez-toc-section-end\"><\/span><\/h3>\n<p>According to placement new, you can implement placement delete. But, remarkably, the C++ runtime will not automatically call placement delete. Therefore, it&#8217;s the programmer&#8217;s duty.<\/p>\n<p>A typically used strategy invokes the destructor in the first step and placement delete in the second step.&nbsp; The destructor deinitializes the object, and placement new deallocates the memory.<\/p>\n<p><!-- HTML generated using hilite.me --><\/p>\n<div style=\"background: #ffffff; overflow: auto; width: auto; gray;border-width: .1em .1em .1em .8em;\">\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #2b91af;\">char<\/span>* memory= <span style=\"color: #0000ff;\">new<\/span> <span style=\"color: #2b91af;\">char<\/span>[<span style=\"color: #0000ff;\">sizeof<\/span>(Account)];\nAccount* a= <span style=\"color: #0000ff;\">new<\/span>(memory) Account;  <span style=\"color: #008000;\">\/\/ placement new<\/span>\n...\na-&gt;~Account();                    <span style=\"color: #008000;\">\/\/ destructor<\/span>\n<span style=\"color: #0000ff;\">operator<\/span> delete(a,memory);        <span style=\"color: #008000;\">\/\/ placement delete\n<\/span>\n<\/pre>\n<\/div>\n<p>Of course, according to statements and strategies, the usage of placement delete for C arrays holds.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Whats_next\"><\/span>What&#8217;s next?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>The plan is crystal clear. In the<a href=\"https:\/\/www.modernescpp.com\/index.php\/overloading-operator-new-and-delete\"> next post, <\/a>I will dig deeper into the overloading of operator new and delete.<span style=\"font-family: courier new,courier;\"><\/span><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Explicit memory management has in C++ a high complexity but also provides great functionality. Sadly, this special domain is not so known in C++. For example, you can directly create objects in static memory, in a reserved area, or even a memory pool. That is functionality, which is often key in safety-critical applications in the [&hellip;]<\/p>\n","protected":false},"author":21,"featured_media":8267,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[364],"tags":[498,493],"class_list":["post-5104","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-embedded","tag-memory","tag-new-delete"],"_links":{"self":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5104","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=5104"}],"version-history":[{"count":2,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5104\/revisions"}],"predecessor-version":[{"id":8268,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/posts\/5104\/revisions\/8268"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media\/8267"}],"wp:attachment":[{"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/media?parent=5104"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/categories?post=5104"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.modernescpp.com\/index.php\/wp-json\/wp\/v2\/tags?post=5104"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}