{"id":82229,"date":"2021-07-23T09:00:37","date_gmt":"2021-07-23T03:30:37","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=82229"},"modified":"2021-07-23T09:00:37","modified_gmt":"2021-07-23T03:30:37","slug":"cpp-dynamic-memory-allocation","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/","title":{"rendered":"Dynamic Memory Allocation in C++"},"content":{"rendered":"<p>This article covers dynamic memory allocation in C++. We will learn the use of new and delete operators.<\/p>\n<h3>Memory Allocation in C++<\/h3>\n<p>Memory architecture for a C++ program includes<\/p>\n<ul>\n<li><strong>Code Segment<\/strong>: This segment contains the executable code of the program.<\/li>\n<li><strong>Data Segment<\/strong>: It contains the global and static variables of the program.<\/li>\n<li><strong>Stack:<\/strong> It is the part of memory used for static memory allocation. The normal variables in a function are allocated stack space during compilation.<\/li>\n<li><strong>Heap<\/strong>: Also known as the free store, it is the unused part of memory. It is used to dynamically allocate memory at runtime.<\/li>\n<\/ul>\n<h3>Static Memory Allocation in C++<\/h3>\n<p>In static memory allocation, memory is allocated and deallocated by the compiler on its own. We need to define the required size of memory at the time of compilation.<\/p>\n<h3>Dynamic Memory Allocation in C++<\/h3>\n<p>In dynamic memory allocation, memory is allocated during runtime. But, in this case, it is the responsibility of a programmer to deallocate the dynamically allocated memory when it\u2019s no longer in use. Otherwise, it leads to memory leaks.<\/p>\n<h4>Uses of Dynamic Memory Allocation<\/h4>\n<ul>\n<li>There are times when we do not know in advance the amount of memory required to store some data. Using dynamic memory allocation, we can allocate memory of variable size at runtime.<\/li>\n<li>It provides flexibility to the programmer. Programmers can allocate and deallocate memory as and when needed.<\/li>\n<\/ul>\n<p>In C, we use malloc() and calloc() functions to dynamically allocate memory. To deallocate that memory, we use free(). These functions are supported in C++ as well. But, it is suggested to avoid using these functions in C++.<br \/>\nC++ provides two unary operators, new and delete, to dynamically allocate and deallocate memory efficiently.<\/p>\n<h3>New Operator in C++<\/h3>\n<p>New operator serves requests to allocate memory on the heap. It allocates the memory if enough memory is available. Then, it returns the address of the newly allocated and initialised memory space to the pointer variable.<\/p>\n<p>For any data type, syntax to dynamically allocate memory is<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pointer_variable = new data_type;\n<\/pre>\n<p>Here,<\/p>\n<ul>\n<li>pointer_variable is a pointer whose type is data_type.<br \/>\ndata_type can either be any built-in data type including array or any user-defined data type like structure and class.<\/li>\n<\/ul>\n<p><strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int *ptr = NULL;\t\/\/pointer ptr initialised with NULL\nptr = new int;\t\t\/\/requests memory\n<\/pre>\n<p>This can be combined and written in a single line as<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int *ptr = new int;\n<\/pre>\n<p>Syntax to initialise memory with new operator:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pointer_variable = new data_type(value);<\/pre>\n<p><strong>For example,<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int *ptr = new int(10);<\/pre>\n<p>Note that pointers play an important role in dynamic memory allocation.<\/p>\n<h4>If enough memory is not available in the heap<\/h4>\n<p>If the heap does not have enough memory, an exception of type std::bad_alloc is thrown indicating request failure. So, we use \u2018nothrow&#8217; with the new operator as then the new operator returns NULL.<\/p>\n<p>It is a good practice to check if the returned pointer is NULL.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">int *ptr = new(nothrow) int;\nif (!ptr) {\n  cout&lt;&lt; \u201cFailed! Memory not available.\u201d&lt;&lt;endl;\n  exit(1);\n}\n<\/pre>\n<h3>Delete Operator in C++<\/h3>\n<p>Delete operator frees the dynamically allocated memory when it\u2019s no longer in use.<\/p>\n<p><strong>Syntax<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">delete pointer_variable;\t\t\/\/Releases memory pointed to by pointer_variable<\/pre>\n<p><strong>Example of dynamic memory allocation in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint main() {\n  int *ptr = new(nothrow) int;\n  \n  if(!ptr){\n      cout&lt;&lt;\"Failed! Memory not available.\"&lt;&lt;endl;\n      exit(1);\n  }\n  \n  *ptr = 100;\n  \n  cout&lt;&lt;\"Value = \"&lt;&lt;*ptr;\n  \n  delete ptr;\n  return 0;\n}<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Value = 100<\/div>\n<h3>C++ Dynamic Memory Allocation for Arrays<\/h3>\n<p>Many times, we are not sure of the size of an array until runtime. Dynamic memory allocation serves the purpose in such situations. It makes memory management more efficient.<\/p>\n<p>Syntax to allocate a block of memory for an array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pointer_variable = new data_type[size];<\/pre>\n<p>For a multidimensional array of size m x n,<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">pointer_variable = new data_type[m][n];<\/pre>\n<p>Syntax to deallocate the memory occupied by any array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">delete [ ] pointer_variable;\n<\/pre>\n<p><strong>Example of dynamic memory allocation for arrays in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nint main() {\n  int *ptr = new(nothrow) int[10];\n  \n  if(!ptr){\n      cout&lt;&lt;\"Failed! Memory not available.\"&lt;&lt;endl;\n      exit(1);\n  }\n  \n  for(int i=0; i&lt;10; i++){\n      ptr[i]=i+1;\n  }\n  \n  for(int i=0; i&lt;10; i++){\n      cout&lt;&lt;ptr[i]&lt;&lt;\" \";\n  }\n  \n  delete [] ptr;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">1 2 3 4 5 6 7 8 9 10<\/div>\n<h3>Dynamic Memory Allocation for Objects<\/h3>\n<p>We can dynamically allocate memory to objects also.<\/p>\n<p><strong>Example of dynamic memory allocation for objects in C++<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\nclass Test {\n    public:\n    Test() {\n        cout&lt;&lt;\"Constructor\"&lt;&lt;endl;\n    }\n    ~Test() {\n        cout&lt;&lt;\"Destructor\"&lt;&lt;endl;\n    }\n};\nint main() {\n  Test *t = new Test[3];\n  delete [] t;\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Constructor<br \/>\nConstructor<br \/>\nConstructor<br \/>\nDestructor<br \/>\nDestructor<br \/>\nDestructor<\/div>\n<p>Observe that since we allocated an array of three Test objects, constructor is called thrice. Similarly, while freeing these objects, destructor is also called thrice.<\/p>\n<h3>Dangling Pointer<\/h3>\n<p>A dangling pointer is a pointer that points to a memory address that has been freed (or deallocated).<\/p>\n<h3>Summary<\/h3>\n<p>In this article, we learnt how to dynamically allocate memory in C++ using examples. Firstly, we learnt the types of memory allocation. Then we discussed the uses of dynamic memory allocation.<\/p>\n<p>C++ provides new and delete operators to dynamically allocate and deallocate memory respectively. Then, we discussed dynamic memory allocation for arrays and objects.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This article covers dynamic memory allocation in C++. We will learn the use of new and delete operators. Memory Allocation in C++ Memory architecture for a C++ program includes Code Segment: This segment contains&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":82936,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[3836,3837,3838,3839],"class_list":["post-82229","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-c-dynamic-memory-allocation","tag-delete-operator-in-c","tag-dynamic-memory-allocation-in-c","tag-new-operator-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Dynamic Memory Allocation in C++ - TechVidvan<\/title>\n<meta name=\"description\" content=\"Learn how to dynamically allocate memory in C++ using examples. New &amp; delete operators help to dynamically allocate &amp; deallocate memory.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Dynamic Memory Allocation in C++ - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"Learn how to dynamically allocate memory in C++ using examples. New &amp; delete operators help to dynamically allocate &amp; deallocate memory.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-07-23T03:30:37+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Dynamic-Memory-Allocation.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Dynamic Memory Allocation in C++ - TechVidvan","description":"Learn how to dynamically allocate memory in C++ using examples. New & delete operators help to dynamically allocate & deallocate memory.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/","og_locale":"en_US","og_type":"article","og_title":"Dynamic Memory Allocation in C++ - TechVidvan","og_description":"Learn how to dynamically allocate memory in C++ using examples. New & delete operators help to dynamically allocate & deallocate memory.","og_url":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-07-23T03:30:37+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Dynamic-Memory-Allocation.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Dynamic Memory Allocation in C++","datePublished":"2021-07-23T03:30:37+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/"},"wordCount":689,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Dynamic-Memory-Allocation.jpg","keywords":["C++ Dynamic Memory Allocation","delete operator in c++","Dynamic Memory Allocation in C++","new operator in c++"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/","url":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/","name":"Dynamic Memory Allocation in C++ - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Dynamic-Memory-Allocation.jpg","datePublished":"2021-07-23T03:30:37+00:00","description":"Learn how to dynamically allocate memory in C++ using examples. New & delete operators help to dynamically allocate & deallocate memory.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Dynamic-Memory-Allocation.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Dynamic-Memory-Allocation.jpg","width":1200,"height":628,"caption":"C++ Dynamic Memory Allocation"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/cpp-dynamic-memory-allocation\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Dynamic Memory Allocation in C++"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/82229","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=82229"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/82229\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/82936"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=82229"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=82229"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=82229"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}