CINXE.COM

Dynamic Memory Allocation in C++ - Scaler Topics

<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width"/><title>Dynamic Memory Allocation in C++ - Scaler Topics</title><link rel="canonical" href="https://www.scaler.com/topics/cpp/dynamic-memory-allocation-in-cpp/"/><meta name="robots" content="max-snippet:-1, max-video-preview:-1, max-image-preview:large"/><meta name="description" content="In this article by Scaler Topics, we will see an explanation of memory management and types of memory (stack and heap) in C++ Language, read to know more."/><meta name="author" content="Abhishek Chandra"/><meta name="category" content="C++"/><meta property="og:type" content="article"/><meta property="og:title" content="Dynamic Memory Allocation in C++ - Scaler Topics"/><meta property="og:description" content="In this article by Scaler Topics, we will see an explanation of memory management and types of memory (stack and heap) in C++ Language, read to know more."/><meta property="og:url" content="https://www.scaler.com/topics/cpp/dynamic-memory-allocation-in-cpp/"/><meta property="og:site_name" content="Scaler Topics"/><meta property="og:image" content="https://www.scaler.com/topics/images/dynamics-memory-allocation-in-cpp.webp"/><meta property="og:image:secure_url" content="https://www.scaler.com/topics/images/dynamics-memory-allocation-in-cpp.webp"/><meta property="og:image:width" content="1680"/><meta property="og:image:height" content="296"/><meta property="og:image:alt" content="Dynamic Memory Allocation in C++ - Scaler Topics"/><meta property="article:published_time" content="2022-12-14T00:00:00.000Z"/><meta name="twitter:site" content="@ScalerTopics"/><meta name="twitter:card" content="summary_large_image"/><meta name="twitter:title" content="Dynamic Memory Allocation in C++ - Scaler Topics"/><meta name="twitter:description" content="In this article by Scaler Topics, we will see an explanation of memory management and types of memory (stack and heap) in C++ Language, read to know more."/><meta name="twitter:image" content="https://www.scaler.com/topics/images/dynamics-memory-allocation-in-cpp.webp"/><meta name="twitter:label1" content="Written by"/><meta name="twitter:data1" content="Abhishek Chandra"/><meta name="twitter:label2" content="Time to read"/><meta name="twitter:data2" content="7 mins"/><meta name="next-head-count" content="28"/><link rel="icon" href="/topics/favicon.ico"/><link rel="preconnect" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics"/><link rel="dns-prefetch" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics"/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/media/0ac14a3c407fb3c4-s.p.woff2" as="font" type="font/woff2" crossorigin="anonymous" data-next-font="size-adjust"/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/media/fc6fba7ce0876fef-s.p.woff2" as="font" type="font/woff2" crossorigin="anonymous" data-next-font="size-adjust"/><script id="article-schema" type="application/ld+json" data-nscript="beforeInteractive" crossorigin="anonymous">{ "@context": "https://schema.org", "@type": "Article", "mainEntityOfPage": { "@type": "WebPage", "@id": "https://www.scaler.com/topics/cpp/dynamic-memory-allocation-in-cpp/" }, "headline": "Dynamic Memory Allocation in C++ - Scaler Topics", "image": { "@type": "ImageObject", "url": ["https://www.scaler.com/topics/images/dynamics-memory-allocation-in-cpp.webp","https://scaler.com/topics/images/types-of-memory.webp","https://scaler.com/topics/images/dynamic-memory-allocation-in-cpp.webp"] }, "datePublished": "2022-12-14T00:00:00.000Z", "dateModified": "2022-12-14T00:00:00.000Z", "author": [{"@type":"Person","name":"Abhishek Chandra","url":"https://www.scaler.com/topics/author/abhishek-chandra","image":"https://lh3.googleusercontent.com/a-/ACNPEu9R2U96t1_I8R2LHopumh5WPRIBtvEDc_P5RKBLPE8=s96-c","jobTitle":"Technical Writer","sameAs":["https://www.linkedin.com/in/abhishek-chandra1/"]}], "publisher": { "@type": "Organization", "name": "Scaler Topics", "logo": { "@type": "ImageObject", "url": "https://www.scaler.com/topics/media/Scaler_Topics-1.png" } }, "description": "In this article by Scaler Topics, we will see an explanation of memory management and types of memory (stack and heap) in C++ Language, read to know more.", "articleSection": "C++", "url": "https://www.scaler.com/topics/cpp/dynamic-memory-allocation-in-cpp/", "wordCount": 1543, "inLanguage": "en-IN" }</script><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/d534126c2b78fa37.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/d534126c2b78fa37.css" crossorigin="anonymous" data-n-g=""/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/4c0f02e37a44e2c9.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/4c0f02e37a44e2c9.css" crossorigin="anonymous" data-n-p=""/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/7c735c05af084bb2.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/7c735c05af084bb2.css" crossorigin="anonymous" data-n-p=""/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/165fa169e424a2ec.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/165fa169e424a2ec.css" crossorigin="anonymous" data-n-p=""/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/f904c36152107389.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/f904c36152107389.css" crossorigin="anonymous" data-n-p=""/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/141113e96b07b13e.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/141113e96b07b13e.css" crossorigin="anonymous" data-n-p=""/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/65c6437e87287556.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/65c6437e87287556.css" crossorigin="anonymous"/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/47797229093bb63c.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/47797229093bb63c.css" crossorigin="anonymous"/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/1814549219ea178a.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/1814549219ea178a.css" crossorigin="anonymous"/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/e39e0ebad6bd5384.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/e39e0ebad6bd5384.css" crossorigin="anonymous"/><link rel="preload" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/a11af346a015967e.css" as="style" crossorigin="anonymous"/><link rel="stylesheet" href="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/css/a11af346a015967e.css" crossorigin="anonymous"/><noscript data-n-css=""></noscript><script defer="" crossorigin="anonymous" nomodule="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/polyfills-c67a75d1b6f99dc8.js"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/5177.02dd537be8ea20b7.js" crossorigin="anonymous"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/3161.b1dc513e17ad7fbe.js" crossorigin="anonymous"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/1177-6d4d7d97dc3dfbce.js" crossorigin="anonymous"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/2401-b7547d978662b2c2.js" crossorigin="anonymous"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/8809.aec60e2150875e0b.js" crossorigin="anonymous"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/1631.e3397086ace007b1.js" crossorigin="anonymous"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/6770.b20921fa9e8bdafa.js" crossorigin="anonymous"></script><script defer="" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/9605.5238782c3d425495.js" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/webpack-7abfde03f144cc2c.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/framework-84476791e5b56604.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/main-ace78b5142fc8917.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/pages/_app-0db0bcdf594c542f.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/2edb282b-ee9378f1d75cffd2.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/413057b3-57a19db2a0fcc17a.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/94a7ad86-20e09c8aeb1be6e9.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/2272ea81-0b4c4d72740c5692.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/9097-3cd3583c3d4b1241.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/3710-83dbb7be4ba9d86a.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/8421-8d137677ba16bee6.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/8972-e0f7e135826ea562.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/8296-3927c311f1301064.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/5022-b7ffe8abea3c8e44.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/4707-c1c0eaa5bd9b5cad.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/8503-14d9a91c6224a3a5.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/2363-c86cdf7c058c5bf6.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/9298-573b4bea3539387f.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/7680-3154c7084bd03149.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/6026-fbadd3343bdbfd36.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/4866-4d5ab945b9c2c819.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/3376-3344d7df8b1a0dff.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/9339-f12a01444de242e8.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/2097-cc5b1739485d6525.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/9757-601f8db2457745d4.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/2022-18e2f6555326d314.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/4992-f276950658be1ccb.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/568-983f8c4802c0313d.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/2023-8536a91be2699bc5.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/chunks/pages/%5B...slug%5D-f0c04271a154a2f7.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/6jK709HyxmpV6buc4IRmo/_buildManifest.js" defer="" crossorigin="anonymous"></script><script src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/_next/static/6jK709HyxmpV6buc4IRmo/_ssgManifest.js" defer="" crossorigin="anonymous"></script></head><body><div id="__next"><div class="__className_2fe30b full-height column"><div class="Header_header_container__uchwV header_items_headerContainer__Ea7gR articleLayout"><div class="Header_header__links__KRM32"><div class="Header_links_container__4fhhe row sr-container"><div class="row flex-ac"><div role="button" tabindex="0" class="signin-alert-popup_signInWrapper__Kr4eW"><div class="signin-alert-popup_overLay__Xq3de"></div><a class="Tappable-module_root__N7ll5 Header_link_item__Jeq_c Header_hide_above_tablet__YBTTX" target="_blank"><div class="Header_exp_scaler_link__nl8_2 Header_exp_scaler__idDAV"><span class="m-r-xxs">Experience</span><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/scalerLogoWhite.svg" alt="Scaler" height="8" width="60" loading="lazy"/></div></a></div><a href="https://www.scaler.com/?utm_source=topics" class="Header_link_item__Jeq_c Header_hide_below_desktop__JfhVe" target="_blank"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/scalerLogoWhite.svg" alt="Scaler" height="8" width="60" loading="lazy"/></a><div class="Header_item_separator__qyfwr"></div></div><div class="row flex-ac"><a href="https://www.scaler.com/academy/?utm_source=topics" class="Header_link_item__Jeq_c" target="_blank">Academy</a><div class="Header_item_separator__qyfwr"></div></div><div class="row flex-ac"><a href="https://www.scaler.com/data-science-course/?utm_source=topics" class="Header_link_item__Jeq_c" target="_blank">Data Science</a><div class="Header_item_separator__qyfwr"></div></div><div class="row flex-ac"><a href="https://www.scaler.com/neovarsity/?utm_source=topics" class="Header_link_item__Jeq_c" target="_blank">Neovarsity</a></div></div></div><div class="Header_header__scmTs sr-container header_items_article_nav_header__p39r4"><div class="Header_header__branding__lJ8b8"><a class="header__logo Header_logo__YtLXM" href="/topics/"><img class="Header_header__logo_img__Uiby_ show-in-tablet" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/topic_logo.svg" alt="Scaler Topics Logo" width="32" height="32"/><img loading="lazy" class="Header_header__logo_img__Uiby_ hide-in-tablet" src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/ScalerTopics_Logo.svg" alt="Scaler Topics Logo" height="64" width="120"/></a></div><div class="Header_middle_items__oV5uq header_items_middleItem__6JSjC"><div class="full-width Header_header__content__8w1ZO"><div class="header_items_headItems__qhL4j"><div class="header_items_headLinks__y1htd"><div><div class="dropdown"><a class="tappable dropdown__title header_items_header_title__y_fDv"><div class="header_items_header_middle_item__Pyg_d"><span class="m-r-5">Topics</span><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__down__hhjJu header_items_dropdown_icon__F__ut hide-in-mobile" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg></div></a></div></div><div><div class="dropdown"><a class="Tappable-module_root__N7ll5 dropdown__title header_items_header_title__y_fDv"><div class="header_items_header_middle_item__Pyg_d"><span class="m-r-5">Explore</span><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__down__hhjJu header_items_dropdown_icon__F__ut hide-in-mobile" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg></div></a></div></div><div class="row flex-ac header_items_skillTest__container__IVXbl"><div class="dropdown"><a class="tappable dropdown__title header_items_header_title__y_fDv"><div class="relative header_items_header_middle_item__Pyg_d"><div class="row flex-c absolute header_items_header__newTag__A3Rrw tag_tag_container__aoQqR">New</div><div class="row flex-ac m-r-5">Skill Test</div><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__down__hhjJu header_items_dropdown_icon__F__ut hide-in-mobile" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg></div></a></div></div><div><div class="dropdown"><a class="tappable dropdown__title header_items_header_title__y_fDv"><div class="header_items_header_middle_item__Pyg_d"><span class="m-r-5">Courses</span><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__down__hhjJu header_items_dropdown_icon__F__ut hide-in-mobile" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg></div></a></div></div><a data-id="header-item" class="header_items_header_middle_item__Pyg_d" role="link" tabindex="0" href="/topics/events/">Free Masterclass</a></div><div class="row flex-ac space-between"><div class="search_searchbarContainer__x3u_B search-bar_headSearch__9JRJh header_items_search_bar__vmysN header_items_search_bar_article__twdVp hide-in-tablet"><div class="search_container__d1rV9 p-15"><svg fill="currentColor" class="search_search_icon__Kr9M1" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M30.243 28.489l-6.719-6.89c1.716-2.097 2.756-4.806 2.756-7.757 0-0.002 0-0.004 0-0.005v0c-0.009-6.821-5.537-12.349-12.357-12.356h-0.001c-6.821 0.009-12.347 5.535-12.356 12.355v0.001c0.007 6.821 5.535 12.349 12.355 12.358h0.001c0.002 0 0.003 0 0.005 0 2.952 0 5.66-1.040 7.779-2.774l-0.022 0.017 6.719 6.89c0.118 0.118 0.28 0.19 0.46 0.19s0.342-0.073 0.46-0.19l0.92-0.92c0.118-0.118 0.19-0.28 0.19-0.46s-0.073-0.342-0.19-0.46v0zM13.922 23.592c-5.384-0.007-9.747-4.371-9.753-9.755v-0.001c0.007-5.384 4.37-9.746 9.753-9.753h0.001c5.385 0.006 9.748 4.369 9.755 9.753v0.001c-0.006 5.385-4.37 9.749-9.755 9.755h-0.001z"></path></svg><div class="Tappable-module_root__N7ll5 search_search_btn__AjpZg" data-testid="input-id1"><span class="search_search_text__80cj0">Search for Articles, Topics</span></div></div></div></div></div></div><div role="button" tabindex="0" class="signin-alert-popup_signInWrapper__Kr4eW"><div class="signin-alert-popup_overLay__Xq3de"></div><a class="Tappable-module_root__N7ll5 Header_link_item__Jeq_c" target="_blank"><div class="Header_exp_scaler_link__nl8_2 Header_exp_scaler__idDAV hide-in-mobile show-in-tablet"><span class="m-r-xxs">Experience</span><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/scalerLogoWhite.svg" alt="Scaler" height="8" width="60" loading="lazy"/></div></a></div><input type="button" class="Header_header_signin__H8u_q cursor hide-in-tablet" value="Sign In"/><div role="button" tabindex="0" class="signin-alert-popup_signInWrapper__Kr4eW"><div class="signin-alert-popup_overLay__Xq3de"></div><a class="Tappable-module_root__N7ll5 Header_exp_scaler__idDAV Header_hide_in_small_screen__rcYLc" target="_blank">Experience Scaler</a></div></div><div class="show-in-tablet show-in-tablet"><button type="button" class="header_items_hamburger_btn__xaYX0 cursor"><svg fill="currentColor" class="header_items_hamburger_icon__3lUyt" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M27.324 14.969h-22.652c-0.569 0-1.029 0.461-1.029 1.029s0.461 1.029 1.029 1.029h22.652c0.569 0 1.029-0.461 1.029-1.029s-0.461-1.029-1.029-1.029v0z"></path><path d="M4.672 8.793h22.652c0.569 0 1.029-0.461 1.029-1.029s-0.461-1.029-1.029-1.029h-22.652c-0.569 0-1.029 0.461-1.029 1.029s0.461 1.029 1.029 1.029v0z"></path><path d="M27.324 23.207h-22.652c-0.569 0-1.029 0.461-1.029 1.029s0.461 1.029 1.029 1.029h22.652c0.569 0 1.029-0.461 1.029-1.029s-0.461-1.029-1.029-1.029v0z"></path></svg></button></div></div></div><main class="mainContainer articlePage articleLayout"><div class="view_view_container__AUfnF"><div class="row flex-jc"><div class="view_left_section__zPSLG"><div class="view_main_container__Id57J view_ar_container__LNAHP"><div><div class="row space-between m-b-xxs"><div class="row"><div class="hide-in-tablet breadcrumb_container__HwKni view_breadcrumb_display__dKFsT"><div data-id="breadcrumb" class="breadcrumb_item__jdd_h" href="/topics/"><div data-tip="Home" data-place="bottom"><svg fill="currentColor" class="breadcrumb_link_icon__28vc6 column flex-ac" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 33 32"><path d="M26.089 27.6h-5.647c-0.001 0-0.002 0-0.003 0-1.033 0-1.871-0.834-1.877-1.866v-5.657c0-0.004-0.004-0.008-0.008-0.008v0h-3.768c-0.004 0-0.008 0.004-0.008 0.008v0 5.656c-0.006 1.032-0.844 1.866-1.876 1.867h-5.652c-1.032-0.002-1.869-0.835-1.875-1.866v-10.897s0-0.011 0-0.015c0.010-0.535 0.238-1.016 0.598-1.358l0.001-0.001 0.013-0.012 9.419-8.56c0.332-0.305 0.778-0.493 1.267-0.493s0.934 0.187 1.268 0.494l-0.001-0.001 9.429 8.569c0.361 0.343 0.589 0.823 0.599 1.357l0 0.002s0 0.011 0 0.015v10.899c-0.006 1.032-0.844 1.867-1.877 1.867-0 0-0.001 0-0.001 0h0zM14.787 18.199h3.768c1.035 0.002 1.873 0.84 1.875 1.875v5.66c0 0.004 0.004 0.008 0.008 0.008v0h5.651c0.004 0 0.008-0.004 0.008-0.008v0-10.883c-0.001-0.010-0.005-0.020-0.012-0.027l0 0-9.421-8.557-9.408 8.549c-0.007 0.007-0.011 0.016-0.012 0.027v10.891c0 0.004 0.004 0.008 0.008 0.008v0h5.651c0.004 0 0.008-0.004 0.008-0.008v0-5.656c0.001-1.036 0.841-1.876 1.877-1.876v0z"></path></svg></div><div class="__react_component_tooltip t5d5a9154-b0e8-46cd-99e3-2e330742e5c6 place-top type-dark" id="t5d5a9154-b0e8-46cd-99e3-2e330742e5c6" data-id="tooltip"><style aria-hidden="true"> .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6 { color: #fff; background: #222; border: 1px solid transparent; border-radius: undefinedpx; padding: 8px 21px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-top { margin-top: -10px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-top::before { content: ""; background-color: inherit; position: absolute; z-index: 2; width: 20px; height: 12px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-top::after { content: ""; position: absolute; width: 10px; height: 10px; border-top-right-radius: undefinedpx; border: 1px solid transparent; background-color: #222; z-index: -2; bottom: -6px; left: 50%; margin-left: -6px; transform: rotate(135deg); } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-bottom { margin-top: 10px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-bottom::before { content: ""; background-color: inherit; position: absolute; z-index: -1; width: 18px; height: 10px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-bottom::after { content: ""; position: absolute; width: 10px; height: 10px; border-top-right-radius: undefinedpx; border: 1px solid transparent; background-color: #222; z-index: -2; top: -6px; left: 50%; margin-left: -6px; transform: rotate(45deg); } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-left { margin-left: -10px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-left::before { content: ""; background-color: inherit; position: absolute; z-index: -1; width: 10px; height: 18px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-left::after { content: ""; position: absolute; width: 10px; height: 10px; border-top-right-radius: undefinedpx; border: 1px solid transparent; background-color: #222; z-index: -2; right: -6px; top: 50%; margin-top: -6px; transform: rotate(45deg); } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-right { margin-left: 10px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-right::before { content: ""; background-color: inherit; position: absolute; z-index: -1; width: 10px; height: 18px; } .t5d5a9154-b0e8-46cd-99e3-2e330742e5c6.place-right::after { content: ""; position: absolute; width: 10px; height: 10px; border-top-right-radius: undefinedpx; border: 1px solid transparent; background-color: #222; z-index: -2; left: -6px; top: 50%; margin-top: -6px; transform: rotate(-135deg); } </style></div></div><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__right__YxLYH hide-in-tablet" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg><div class="breadcrumb_seperator__GMDUz show-in-tablet"></div><a data-testid="breadcrumbs-id" href="/topics/hubs/"><div data-id="breadcrumb" data-tip="" data-place="bottom" class="breadcrumb_item__jdd_h"><div data-tip="Reading Tracks" data-place="bottom"><svg fill="currentColor" stroke="" class="breadcrumb_link_icon__28vc6 column flex-ac" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M14 16.56c-0.309 0-0.56-0.251-0.56-0.56v0-12c0-0.309 0.251-0.56 0.56-0.56s0.56 0.251 0.56 0.56v10.88l3.104-2.328c0.092-0.070 0.209-0.112 0.336-0.112s0.244 0.042 0.337 0.113l-0.001-0.001 3.104 2.328v-10.88c0-0.309 0.251-0.56 0.56-0.56s0.56 0.251 0.56 0.56v12c0 0.309-0.251 0.56-0.56 0.56-0.127 0-0.244-0.042-0.337-0.113l0.001 0.001-3.664-2.748-3.664 2.748c-0.092 0.070-0.209 0.112-0.336 0.112v0z"></path><path d="M6 27.56c-0.309 0-0.56-0.251-0.56-0.56v0-20c0-0 0-0.001 0-0.001 0-0.983 0.397-1.873 1.040-2.519l-0 0c0.638-0.642 1.523-1.040 2.5-1.040 0.003 0 0.006 0 0.010 0h17.011c0.309 0 0.56 0.251 0.56 0.56v0 20c0 0.309-0.251 0.56-0.56 0.56v0h-17.013c0 0-0 0-0 0-1.337 0-2.421 1.080-2.427 2.415v0.025c0 0.309-0.251 0.56-0.56 0.56v0zM8.987 4.56c-0.002 0-0.004 0-0.007 0-0.668 0-1.273 0.272-1.71 0.711l-0 0c-0.439 0.442-0.711 1.051-0.711 1.723 0 0.001 0 0.002 0 0.003v-0 17.402c0.629-0.595 1.48-0.96 2.416-0.96 0.004 0 0.008 0 0.012 0h16.453v-18.88z"></path><path d="M24 28.56h-18c-0.309 0-0.56-0.251-0.56-0.56v0-1c0-0.309 0.251-0.56 0.56-0.56s0.56 0.251 0.56 0.56v0 0.44h17.44c0.309 0 0.56 0.251 0.56 0.56s-0.251 0.56-0.56 0.56v0z"></path></svg></div></div></a><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__right__YxLYH hide-in-tablet" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg><div class="breadcrumb_seperator__GMDUz show-in-tablet"></div><a data-testid="breadcrumbs-id" href="/topics/cpp/"><div data-id="breadcrumb" data-tip="C++ Tutorial" data-place="bottom" class="breadcrumb_item__jdd_h breadcrumb_article_title_second_last__Udroe">C++ Tutorial</div></a><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__right__YxLYH hide-in-tablet breadcrumb_isLastSeparator__nSYW7" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg><div class="breadcrumb_seperator__GMDUz show-in-tablet breadcrumb_isLastSeparator__nSYW7"></div><div data-id="breadcrumb" data-tip="" data-place="bottom" class="breadcrumb_item__jdd_h breadcrumb_isLast__v_LIa breadcrumb_title_display__TIbaq breadcrumb_article_title_last__OySmK">Dynamic Memory Allocation in C++</div></div><div class="show-in-tablet breadcrumb_mobile_container__JPiqx view_breadcrumb_display__dKFsT"><div class="row flex-ac" aria-hidden="true"><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__left__TwvkN breadcrumb_back_icon__a6Usx" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg><div class="breadcrumb_title_display__TIbaq breadcrumb_article_title_last__OySmK">Dynamic Memory Allocation in C++</div></div></div></div><div class="row align-c view_util_wrapper__VJgtk"><div role="button" tabindex="0" class="signin-alert-popup_signInWrapper__Kr4eW"><div class="signin-alert-popup_overLay__Xq3de"></div><a class="Tappable-module_root__N7ll5 row cheatsheet_cheatsheet_btn__OjmuY" target="_blank"><div class="row flex-c"><svg fill="currentColor" class="cheatsheet_cheatsheet_btn__download_icon__yjWYo" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 36 28"><path d="M10.043 13.043c0.391-0.391 1.024-0.391 1.414 0l4.543 4.543 4.543-4.543c0.391-0.391 1.024-0.391 1.414 0s0.39 1.024 0 1.414l-5.25 5.25c-0.391 0.39-1.024 0.39-1.414 0l-5.25-5.25c-0.391-0.391-0.391-1.024 0-1.414z"></path><path d="M16 4c0.552 0 1 0.448 1 1v14c0 0.552-0.448 1-1 1s-1-0.448-1-1v-14c0-0.552 0.448-1 1-1z"></path><path d="M5 18c0.552 0 1 0.448 1 1v7h20v-7c0-0.552 0.448-1 1-1s1 0.448 1 1v7c0 0.53-0.211 1.039-0.586 1.414s-0.884 0.586-1.414 0.586h-20c-0.53 0-1.039-0.211-1.414-0.586s-0.586-0.884-0.586-1.414v-7c0-0.552 0.448-1 1-1z"></path></svg></div><span class=""><span class="cheatsheet_cheatsheet_btn__text__lWQa7">C++</span> <!-- -->Cheatsheet</span></a></div><div class="shareButton_share__Vm9x8 shareButton_buttonHover__AmSQt row flex-c"><svg fill="currentColor" class="" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M8 11.333c2.577 0 4.667 2.089 4.667 4.667s-2.089 4.667-4.667 4.667c-2.577 0-4.667-2.089-4.667-4.667v0c0-2.577 2.089-4.667 4.667-4.667v0zM8 19.333c1.841 0 3.333-1.492 3.333-3.333s-1.492-3.333-3.333-3.333c-1.841 0-3.333 1.492-3.333 3.333v0c0 1.841 1.492 3.333 3.333 3.333v0z"></path><path d="M22 20.333c2.577 0 4.667 2.089 4.667 4.667s-2.089 4.667-4.667 4.667c-2.577 0-4.667-2.089-4.667-4.667v0c0-2.577 2.089-4.667 4.667-4.667v0zM22 28.333c1.841 0 3.333-1.492 3.333-3.333s-1.492-3.333-3.333-3.333c-1.841 0-3.333 1.492-3.333 3.333v0c0 1.841 1.492 3.333 3.333 3.333v0z"></path><path d="M22 2.333c2.577 0 4.667 2.089 4.667 4.667s-2.089 4.667-4.667 4.667c-2.577 0-4.667-2.089-4.667-4.667v0c0-2.577 2.089-4.667 4.667-4.667v0zM22 10.333c1.841 0 3.333-1.492 3.333-3.333s-1.492-3.333-3.333-3.333c-1.841 0-3.333 1.492-3.333 3.333v0c0 1.841 1.492 3.333 3.333 3.333v0z"></path><path d="M11.364 14.505c-0 0-0 0-0 0-0.234 0-0.441-0.121-0.56-0.304l-0.002-0.003c-0.066-0.102-0.106-0.227-0.106-0.361 0-0.234 0.121-0.44 0.303-0.559l0.003-0.002 7.272-4.675c0.102-0.066 0.227-0.106 0.361-0.106 0.234 0 0.44 0.121 0.559 0.303l0.002 0.003c0.066 0.102 0.106 0.227 0.106 0.361 0 0.234-0.121 0.44-0.303 0.559l-0.003 0.002-7.272 4.675c-0.102 0.067-0.226 0.106-0.36 0.107h-0z"></path><path d="M18.635 23.503c-0 0-0 0-0 0-0.134 0-0.258-0.039-0.362-0.107l0.003 0.002-7.271-4.675c-0.186-0.12-0.307-0.327-0.307-0.561 0-0.134 0.039-0.258 0.107-0.363l-0.002 0.003c0.12-0.186 0.327-0.307 0.561-0.307 0.134 0 0.258 0.039 0.363 0.107l-0.003-0.002 7.272 4.675c0.186 0.12 0.307 0.327 0.307 0.561 0 0.368-0.298 0.667-0.667 0.667-0.001 0-0.001 0-0.002 0h0z"></path></svg></div></div></div><h1 class="view_title__pgLhk">Dynamic Memory Allocation in C++</h1><div class="full-width m-t-xxs"><div class="article-author_author_name__C_DzB">By <!-- -->Abhishek Chandra</div><div class="article-author_article_time_detail__SHs2n row flex-ac m-b-xs"><span class="flex-c column">7 mins<!-- --> <!-- -->read</span><span class="row flex-c"><div class="article-author_dot_icon__aXBV3 m-r-s"></div><span class="">Last updated: <!-- -->17 Apr 2024</span></span><span class="row flex-c"><div class="article-author_dot_icon__aXBV3 m-r-s"></div><span class="">989<!-- --> views</span></span></div></div><div><div class="row flex-ac space-between full-width p-l-xxs m-b-xs h2 articleWidget_articleWidget__heading___Kzbi"><div class="row flex-ac"><div class="bold">Learn via video course</div><div class="row flex-c bold p-h-xxs m-l-xxs articleWidget_free__tag__vIwTN"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/free.svg" height="12" width="12" loading="lazy"/><span>FREE</span></div></div><a class="Tappable-module_root__N7ll5 row flex-ac hide-in-tablet h6 articleWidget_articleWidget__allCourses__AYnp4" data-name="courses" data-id="explore_all_courses" href="/topics/courses/"><div>View all courses</div><svg fill="currentColor" class="icons_icon_arrow__2GBht icons_icon_arrow__right__WUCHP" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 32 32"><path d="M5.313 16l10.688-10.688 10.688 10.688-1.938 1.875-7.438-7.438v16.25h-2.625v-16.25l-7.5 7.438z"></path></svg></a></div><div class="m-t-xs full-width"><div class="hide-in-mobile"><div class="row flex-c m-b-s commonStyles_course__5KIBa"><div class="row full-width commonStyles_course__details__VTAiI"><img src="https://www.scaler.com/topics/images/instructor-prateek.webp" alt="C++ Course: Learn the Essentials" class="commonStyles_course__image__nuZPe" width="96" height="96" loading="lazy"/><div class="row flex-ac space-between p-h-xs flex-fill full-width"><div class="column full-width"><div class="bold h5 commonStyles_course__title__YnVda">C++ Course: Learn the Essentials</div><div class="row flex-ac m-t-xxs"><div class="commonStyles_course__instructor__4rwsk row align-c bold h6">by <span class="bold p-l-5">Prateek Narang</span></div><div class="m-h-xxs commonStyles_course__divider__UuloR"></div><div class="row align-c"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/user-circle-check.svg" height="16" width="16" loading="lazy"/><div class="h6 commonStyles_course__users__tth8m">1000</div></div><div class="m-h-xxs commonStyles_course__divider__UuloR"></div><div class="row align-c"><svg fill="currentColor" class="commonStyles_course__star__1Giwp" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 32 32"><path d="M7.569 30.625c-0.335 0-0.667-0.103-0.949-0.309-0.529-0.382-0.775-1.039-0.631-1.675l1.963-8.65-6.659-5.84c-0.489-0.427-0.676-1.104-0.475-1.724 0.201-0.618 0.747-1.056 1.395-1.115l8.811-0.8 3.485-8.153c0.257-0.599 0.843-0.986 1.492-0.986 0.651 0 1.235 0.386 1.492 0.983l3.484 8.155 8.81 0.8c0.649 0.058 1.195 0.497 1.397 1.115 0.201 0.619 0.014 1.296-0.476 1.724l-6.659 5.839 1.964 8.651c0.144 0.636-0.102 1.293-0.63 1.675-0.527 0.381-1.229 0.411-1.783 0.078l-7.598-4.541-7.598 4.543c-0.257 0.153-0.544 0.23-0.832 0.23z"></path></svg><div class="h6 commonStyles_course__rating__z4fFS">5</div></div></div></div><a class="tappable commonStyles_learning_button__JYLbC full-width hide-in-tablet h6 commonStyles_course__button__S_dPP" href="/topics/course/cpp-beginners/">Start Learning </a></div></div><div class="show-in-tablet hide-in-mobile full-width m-b-xxs"><div class="row commonStyles_course__button_container__AXSRL"><a class="tappable commonStyles_learning_button__JYLbC full-width row h6 commonStyles_course__button__S_dPP commonStyles_course__button_start__sqRBe" href="/topics/course/cpp-beginners/">Start Learning </a><a class="Tappable-module_root__N7ll5 row h6 commonStyles_course__button__S_dPP commonStyles_course__button_view__I1sQA" data-name="courses" data-id="explore_all_courses" href="/topics/courses/">View all courses<svg fill="currentColor" class="icons_icon_arrow__2GBht icons_icon_arrow__right__WUCHP m-l-xxs" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 32 32"><path d="M5.313 16l10.688-10.688 10.688 10.688-1.938 1.875-7.438-7.438v16.25h-2.625v-16.25l-7.5 7.438z"></path></svg></a></div></div></div></div><div class="show-in-mobile"><div class="column space-between"><div class="row flex-ac mobile_course__container__V2Cw_"><img src="https://www.scaler.com/topics/images/instructor-prateek.webp" alt="C++ Course: Learn the Essentials" width="84" height="84" class="mobile_mobile_cover_img__tl6Lf" loading="lazy"/><div class="column p-t-xxs mobile_course__details_inArticle__jS5sf"><span class="mobile_course_details_title__r6JOj mobile_course_details_title_inArticle___zldf bold">C++ Course: Learn the Essentials</span><div class="row flex-ac m-t-xxs mobile_data__container_inArticle__LlP8z"><span class="mobile_instructor_inArticle__FO1Rg">by <!-- -->Prateek Narang</span><div class="m-h-xxs mobile_divider__FFVtB"></div><div class="row align-c"><svg fill="currentColor" class="mobile_icon__user__HXGxc" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 32 32"><path d="M15.004 11.5c-2.2 0-4 1.8-4 4s1.8 4 4 4 4-1.8 4-4-1.8-4-4-4zM9.004 15.5c0-3.3 2.7-6 6-6s6 2.7 6 6-2.7 6-6 6-6-2.7-6-6z"></path><path d="M15.004 21.5c-1.5 0-2.9 0.4-4.2 1.2s-2.3 1.9-2.9 3.2c-0.3 0.5-0.9 0.7-1.3 0.4-0.6-0.2-0.8-0.8-0.5-1.3 0.8-1.6 2.1-3 3.7-4s3.4-1.5 5.2-1.5c1.8 0 3.7 0.5 5.2 1.5 1.6 1 2.8 2.3 3.7 4 0.2 0.5 0.1 1.1-0.4 1.3s-1.1 0.1-1.3-0.4c-0.7-1.3-1.7-2.4-2.9-3.2-1.4-0.8-2.8-1.2-4.3-1.2z"></path><path d="M15.004 29.5c-0.8 0-1.7-0.1-2.5-0.3-2.5-0.5-4.8-1.7-6.7-3.6-1.8-1.7-3-4-3.5-6.6-0.6-2.5-0.3-5.1 0.7-7.5s2.6-4.4 4.8-5.8c2.1-1.4 4.6-2.2 7.2-2.2 0.7 0 1.4 0.1 2 0.2 0.5 0.1 0.9 0.6 0.8 1.1s-0.6 0.9-1.1 0.8c-0.6-0.1-1.1-0.1-1.7-0.1-2.2 0-4.3 0.6-6.1 1.9-1.8 1.2-3.2 2.9-4.1 4.9s-1.1 4.2-0.6 6.4c0.4 2.1 1.5 4.1 3 5.6s3.5 2.6 5.6 3c2.1 0.4 4.3 0.2 6.4-0.6 2-0.8 3.7-2.2 4.9-4.1 1.2-1.8 1.9-3.9 1.9-6.1 0-1.3-0.2-2.5-0.6-3.7-0.2-0.5 0.1-1.1 0.6-1.3s1.1 0.1 1.3 0.6c0.5 1.4 0.8 2.9 0.7 4.3 0 2.6-0.8 5.1-2.2 7.2s-3.5 3.8-5.8 4.8c-1.6 0.8-3.3 1.1-5 1.1z"></path><path d="M29.704 2.8c0.4 0.4 0.4 1 0 1.4l-4.7 5c-0.2 0.2-0.5 0.3-0.7 0.3-0.3 0-0.5-0.1-0.7-0.3l-2.3-2.5c-0.4-0.4-0.4-1 0-1.4s1-0.4 1.4 0l1.6 1.7 3.9-4.2c0.4-0.4 1.1-0.4 1.5 0z"></path></svg><span class="mobile_course__info__6TMCv">1000</span></div><div class="m-h-xxs mobile_divider__FFVtB"></div><div class="row flex-ac"><svg fill="currentColor" class="mobile_icon__star__Fn2x0" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 32 32"><path d="M7.569 30.625c-0.335 0-0.667-0.103-0.949-0.309-0.529-0.382-0.775-1.039-0.631-1.675l1.963-8.65-6.659-5.84c-0.489-0.427-0.676-1.104-0.475-1.724 0.201-0.618 0.747-1.056 1.395-1.115l8.811-0.8 3.485-8.153c0.257-0.599 0.843-0.986 1.492-0.986 0.651 0 1.235 0.386 1.492 0.983l3.484 8.155 8.81 0.8c0.649 0.058 1.195 0.497 1.397 1.115 0.201 0.619 0.014 1.296-0.476 1.724l-6.659 5.839 1.964 8.651c0.144 0.636-0.102 1.293-0.63 1.675-0.527 0.381-1.229 0.411-1.783 0.078l-7.598-4.541-7.598 4.543c-0.257 0.153-0.544 0.23-0.832 0.23z"></path></svg><span class="mobile_course__info__6TMCv">5</span></div></div></div></div><a class="tappable commonStyles_learning_button__JYLbC full-width" href="/topics/course/cpp-beginners/">Start Learning </a></div></div></div></div><div class="m-t-s article-outline_outline__0_P6T"><a class="Tappable-module_root__N7ll5 row full-width bold article-outline_outline__heading__YVedg"><svg fill="currentColor" class="icons_icon_chevron__cl99H icons_icon_chevron__right__YxLYH" version="1.1" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 32 32"><path d="M9.875 20.563l-1.875-1.875 8-8 8 8-1.875 1.875-6.125-6.125z"></path></svg><div>Topics Covered</div></a></div><div class="markdown-body"><section class="abstract"><h2 id="overview" level="2">Overview</h2><p>The process of allocating or de-allocating a block of memory during the execution of a program is called <strong>Dynamic Memory Allocation</strong>. The operators <strong>new</strong> and <strong>delete</strong> are utilized for dynamic memory allocation in C++ language, <strong>new</strong> operator is used to allocate a memory block, and <strong>delete</strong> operator is used to de-allocate a memory block which is allocated by using new operator.</p></section> <section class="main"><h2 id="c---program-memory-management" level="2">C++ Program Memory Management</h2><p>When we run a C++ program on our machine, it requires some space to store its instructions (statements), local variables, global variables, and various other <a href="https://www.scaler.com/topics/cpp/functions-in-cpp/" target="_blank" title="">functions in C++</a>. This space required to run a C++ Program is known as <strong>memory</strong> in computers.</p><p>There are <strong>two types of memory</strong> in our system, <strong>Static Memory and Dynamic Memory</strong>.</p><ul> <li> <p><strong>Static Memory:</strong> It is a <strong>constant space</strong> allocated by the operating system during the <strong>compile time</strong> of a C++ program and it internally uses <strong>stack</strong> data structure to manage the static memory allocation. We can&#x27;t reallocate the space consumed by the program until its execution is over.</p> </li> <li> <p><strong>Dynamic Memory:</strong> It is the memory that can be allocated or de-allocated by the operating system during the <strong>run-time</strong> of a C++ program. It is more efficient than static memory because we can <strong>de-allocate and reuse</strong> our memory during the run-time of our program.</p> </li> </ul><p>The memory used by a C++ program can be divided further into four parts:</p><ol> <li>Run-time Stack (Static Memory)</li> <li>Static Data Memory (for Global and Static Variables)</li> <li>Instructions / Statements (Static Memory)</li> <li>Heap (Dynamic Memory)</li> </ol><p><img alt="Types of Memory" loading="eager" width="864" height="200" decoding="async" data-nimg="1" class="markdown_image_container__jjYk1 markdown_loading__y_n2Y" style="color:transparent;height:auto;max-width:100%" src="https://scaler.com/topics/images/types-of-memory.webp"/></p><h3 id="the-stack-memory" level="3">The Stack memory</h3><ul> <li>Our operating system <strong>allocates a constant space</strong> during compile-time of a C++ program, this space is known as <strong>Stack memory</strong>.</li> <li>Stack memory is used to <strong>hold functions</strong>, different variables, and local statements that exist in the function definition.</li> <li>Stack is a part of the static memory in our system and it constitutes the majority of our system&#x27;s static memory.</li> </ul><h3 id="the-heap-memory" level="3">The Heap Memory</h3><ul> <li><strong>Heap memory</strong> is also known as the <strong>dynamic memory</strong> in our system. It can be thought of as a large block of memory that is <strong>expandable and shrinkable</strong> during the execution of a program.</li> <li><strong>Allocation and De-allocation of memory blocks</strong> during the execution of a program can be done using <strong>new</strong> and <strong>delete</strong> operators in C++ (these operators are discussed later in the article).</li> <li>Heap memory can be expanded as long as we do not exhaust the machine memory itself. It is not good from a programming perspective to completely use the machine memory to avoid errors, thus we must use the heap memory carefully.</li> </ul></section> <section class="main"><h2 id="types-of-memory-allocation" level="2">Types of Memory Allocation</h2><h3 id="1--static-memory-allocation-in-c----compile-time-memory-allocation-" level="3">1. Static Memory Allocation in C++ (Compile-time Memory Allocation)</h3><ul> <li>When memory is allocated at compile-time, it is referred to as <strong>Static Memory Allocation</strong>.</li> <li>A fixed space is allocated for the local variables, function calls, and local statements, that <strong>can not</strong> be changed during the execution of the program.</li> <li>We <strong>can not allocate or de-allocate a memory block</strong> once the execution of the program starts.</li> <li>We <strong>can&#x27;t re-use</strong> the static memory while the program is running. As a result, it is less effective.</li> </ul><h3 id="2--dynamic-memory-allocation-in-c----run-time-memory-allocation-" level="3">2. Dynamic Memory Allocation in C++ (Run-time Memory Allocation)</h3><ul> <li>When memory is allocated or de-allocated during run-time, it is referred to as <strong>Dynamic Memory Allocation</strong> in C++.</li> <li>A variable space is allocated that <strong>can</strong> be changed during the execution of the program.</li> <li>We use dynamic/heap memory to allocate and de-allocate a block of memory during the execution of the program using <strong>new</strong> and <strong>delete</strong> operators.</li> <li>We <strong>can</strong> re-use our heap memory during the run-time of our program. As a result, it is highly effective.</li> </ul></section> <div></div> <section class="main"><h2 id="why-dynamic-memory-allocation-" level="2">Why Dynamic Memory Allocation?</h2><p>There were some drawbacks of <strong>stack memory or static memory allocation</strong>, like the space allocated for the stack <strong>can not be expanded</strong> during the execution of a C++ program or we can&#x27;t keep variables in the program till the time we want. So, to overcome these drawbacks, we use the <strong>Dynamic Memory Allocation concepts</strong>.</p><p>Dynamic Memory Allocation is also a very essential topic in the field of <strong>data structures</strong>, and it is utilized practically in all data structures. For example, dynamic arrays, linked lists, queues, trees, stack, etc. uses DMA to allocate and de-allocate memory blocks during the execution of a C++ program.</p></section> <section class="main"><h2 id="how-is-it-different-from-memory-allocated-to-normal-variables-" level="2">How is it Different from Memory Allocated to Normal Variables?</h2><p>The operating system uses static memory allocation for normal data-type variables and arrays, for example, <strong><span class="highlight--red">int r;</span></strong>, <strong><span class="highlight--red">double arr[10];</span></strong>, <strong><span class="highlight--red">char name[20];</span></strong>, etc., the memory is automatically allocated at compile time and de-allocated when the function, block, or program finishes by the operating system.</p><p>The operating system uses dynamic memory allocation in C++ for dynamically allocated variables, for example, <strong><span class="highlight--red">int* ptr = new int;</span></strong>, <strong><span class="highlight--red">int* arr = new int[6];</span></strong>. Dynamically allocated memory does not get de-allocated until the program terminates. So, a programmer must de-allocate the memory, when it is no longer required. Memory leaks can occur when a programmer fails to de-allocate a dynamically allocated memory.</p></section> <section class="main"><h2 id="how-is-memory-allocated/de-allocated-in-c---" level="2">How is Memory Allocated/De-Allocated in C++?</h2><p>In C Language, before allocating or de-allocating memory dynamically (at run-time), we have to include <strong><span class="highlight--red">&lt;stdlib.h&gt;</span></strong> header file to use the library functions like <strong><span class="highlight--red">malloc()</span></strong>, <strong><span class="highlight--red">calloc()</span></strong>, <strong><span class="highlight--red">realloc()</span></strong> and <strong><span class="highlight--red">free()</span></strong>.</p><p>In C++ Language, <strong>new</strong> and <strong>delete</strong> operators are pre-defined in the C++ Standard Library and don&#x27;t require to include any library file for run-time allocation and de-allocation of memory blocks. Although we can use <strong><span class="highlight--red">malloc()</span></strong>, <strong><span class="highlight--red">calloc()</span></strong>, and other functions in C++ as well by adding the <strong><span class="highlight--red">&lt;stdlib.h&gt;</span></strong> header file because of the backward compatibility of C++ with C Language. This article explains the <strong>new</strong> and <strong>delete</strong> operators of the C++ language. Visit <a href="https://www.scaler.com/topics/c/dynamic-memory-allocation-in-c/" target="_blank" title="">Dynamic Memory Allocation in C - Scaler Topics</a> to know more about DMA functions in C Language.</p></section> <section class="main"><h2 id="dynamic-memory-allocation-&amp;-de-allocation-criteria" level="2">Dynamic Memory Allocation &amp; De-allocation Criteria</h2><h3 id="1--creating-the-dynamic-space-in-memory-" level="3">1. Creating the Dynamic Space in Memory.</h3><p>During the dynamic memory allocation in C++, first, we have to create a dynamic space (in the heap memory). We use the <strong>new</strong> operator to create a dynamic space.</p><h3 id="2--storing-its-address-in-a-pointer" level="3">2. Storing its Address in a Pointer</h3><p>Once a <strong>dynamic space</strong> a created, we have to store the address of the <strong>allocated space in a pointer variable</strong> to access and modify the contents of the <strong>memory block</strong>.</p><h3 id="3--deleting-the-allocated-space" level="3">3. Deleting the Allocated Space</h3><p>Once the user does not require the memory block, we delete the allocated space using the <strong>delete</strong> operator to free up the heap memory.</p></section> <section class="main"><h2 id="the-&quot;new&quot;-operator-in-c--" level="2">The &quot;new&quot; operator in C++</h2><p>The <strong>new</strong> operator in C++ is used to <strong>dynamically allocate a block of memory and store its address</strong> in a pointer variable during the execution of a C++ program if enough memory is available in the system.</p><h3 id="syntax-for-&quot;new&quot;-operator:" level="3">Syntax for &quot;new&quot; operator:</h3><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><ul> <li><strong><span class="highlight--red">ptr_var</span></strong> is a pointer, which stores the address of the type <strong><span class="highlight--red">data_type</span></strong>.</li> <li>Any pre-defined data types, like <strong><span class="highlight--red">int</span></strong>, <strong><span class="highlight--red">char</span></strong>, etc., or other user-defined data types, like classes, can be used as the <strong><span class="highlight--red">data_type</span></strong> with the <strong>new</strong> operator.</li> </ul><h3 id="example-c---program:" level="3">Example C++ Program:</h3><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Output:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Explanation:</strong></p><ul> <li>A memory block is allocated using the <strong>new</strong> operator and the address of the memory block has been stored in the <strong><span class="highlight--red">ptr</span></strong> pointer.</li> <li>(<strong><span class="highlight--red">*ptr</span></strong>) represents the value at the allocated memory location. We have assigned <strong><span class="highlight--red">12</span></strong> in the memory using <strong><span class="highlight--red">*ptr = 12</span></strong> expression.</li> </ul><h3 id="initializing-dynamic-memory" level="3">Initializing Dynamic Memory</h3><p><strong>Syntax:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Example C++ program:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Output:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><h3 id="what-happens-if-the-system&#x27;s-memory-runs-out-during-the-execution-of-the-program-" level="3">What Happens if the System&#x27;s Memory Runs out During the Execution of the Program?</h3><p>When there is insufficient memory in the heap segment during the run-time of a C++ program, the new request for allocation fails by throwing an exception of type <strong><span class="highlight--red">std::bad alloc</span></strong>. It can be avoided using a <strong>nothrow</strong> argument with the <strong>new</strong> operator. When we use <strong>nothrow</strong> with <strong>new</strong>, it returns a <strong>NULL</strong> pointer. So, the pointer variable should be checked that is formed by <strong>new</strong> before utilizing it in a program.</p><p><strong>Example:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre></section> <section class="main"><h2 id="the-&quot;delete&quot;-operator-in-c--" level="2">The &quot;delete&quot; Operator in C++</h2><p>The <strong>delete</strong> operator is used to de-allocate the block of memory, which is dynamically allocated using the <strong>new</strong> operator. Since, a programmer must de-allocate a block of memory, once it is not required in the program. So, we have to use the <strong>delete</strong> operator to avoid memory leaks and program crash errors, which occur due to the exhaustion of the system&#x27;s memory.</p><h3 id="syntax:" level="3">Syntax:</h3><p>Syntax to delete a single block of memory:</p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p>Syntax to delete an array of memory:</p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><h3 id="example-c---program:" level="3">Example C++ Program:</h3><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Output:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p>(output garbage value is compiler dependent and will be different at each run)</p><p><strong>Explanation:</strong></p><ul> <li>A memory block for the <strong>stars</strong> pointer is allocated using the <strong>new</strong> operator and the address of the memory block has been stored in the <strong>stars</strong> pointer.</li> <li>We have used the <strong>delete</strong> operator to de-allocate the memory pointed by the <strong>stars</strong> pointer, as it is no longer required in our program.</li> <li>The memory is de-allocated but the <strong>stars</strong> pointer is still pointing to some garbage location in the memory. So, it will show <strong>garbage value</strong> if printed on the output screen. We have assigned <strong>NULL</strong> to the <strong>stars</strong> pointer in the end to avoid the situation of a <a href="https://www.scaler.com/topics/c/dangling-pointer-in-c/" target="_blank" title="">dangling pointer</a>.</li> </ul><p><strong>Image Explanation:</strong> <img alt="Dynamic Memory Allocation in C++" loading="lazy" width="864" height="200" decoding="async" data-nimg="1" class="markdown_image_container__jjYk1 markdown_loading__y_n2Y" style="color:transparent;height:auto;max-width:100%" src="https://scaler.com/topics/images/dynamic-memory-allocation-in-cpp.webp"/></p></section> <div></div> <section class="main"><h2 id="dynamic-memory-allocation-in-c---for-arrays" level="2">Dynamic Memory Allocation in C++ for Arrays</h2><h3 id="allocating-a-block-of-memory-using-the-&quot;new&quot;-operator" level="3">Allocating a Block of Memory Using the &quot;new&quot; Operator</h3><p>The <strong>new</strong> operator can also be used to allocate a block of memory (an array) of any <strong><span class="highlight--red">data_type</span></strong>.</p><p><strong>Syntax:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Example</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><h3 id="standard-array-declaration-vs-using-the-&quot;new&quot;-operator" level="3">Standard Array Declaration vs Using the &quot;new&quot; Operator</h3><p>The most significant distinction between <strong>standard arrays and a dynamically allocated array</strong> is that standard arrays are de-allocated by the <a href="https://www.scaler.com/topics/cpp/online-cpp-compiler/" target="_blank" title=""><strong>online C++ compiler</strong></a> when the function execution finishes or it goes out of scope. While with dynamically allocated arrays, arrays always remain in the memory until either the programmer <strong>de-allocates</strong> them or the program execution finishes.</p><p><strong>Syntax for normal array declaration:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Syntax for dynamically allocated array:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Example C++ Program with <span class="highlight--red">new</span> operator:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Custom Input:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Output:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p>(output garbage values are compiler dependent and different at each run)</p><p><strong>Explanation:</strong></p><ul> <li>We have created a dynamically allocated array using the <strong>new</strong> operator.</li> <li>Then, we have taken input for the array elements from the user and printed the array elements.</li> <li>With the use of the <strong>delete</strong> operator on the array pointer <strong><span class="highlight--red">arr</span></strong>, we have de-allocated the array memory. Now, the array location will contain <strong>garbage values</strong> as seen in the output.</li> </ul></section> <section class="main"><h2 id="dynamic-memory-allocation-in-c---for-objects" level="2">Dynamic Memory Allocation in C++ for Objects</h2><p>We can dynamically allocate memory for objects also. When we create an object of a class, a constructor function is invoked. Constructor is a member function of a class that is used to initialize the object. Also, when the object goes out of scope or gets <strong>de-allocated</strong>, a <strong>destructor</strong> function is invoked. Destructor is also a <strong>class member function</strong> that helps in knowing when the object&#x27;s memory gets <strong>deleted</strong>.</p><p>We use pointers once more for allocating memory to objects.</p><p><strong>Example C++ Program:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Output:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Explanation:</strong> We have created a class <strong>Animal</strong> with <a href="https://www.scaler.com/topics/cpp/constructor-and-destructor-in-cpp/" target="_blank" title="">constructor and destructor</a> member functions. In the <strong><span class="highlight--red">main()</span></strong> function, we have created a <strong>dog</strong> object of class <strong>Animal</strong> using the <strong>new</strong> operator, which invokes the constructor function of the <strong>Animal</strong> class. When we have used the <strong>delete</strong> operator to de-allocate the <strong>dog</strong> object memory, the destructor function is invoked.</p></section> <section class="main"><h2 id="comparison-with-&quot;malloc--&quot;,-&quot;calloc--&quot;,-and-&quot;free--&quot;-functions-of-c-" level="2">Comparison with &quot;malloc()&quot;, &quot;calloc()&quot;, and &quot;free()&quot; Functions of C.</h2><p>First, let&#x27;s see the small definitions of <strong><span class="highlight--red">malloc()</span></strong>, <strong><span class="highlight--red">calloc()</span></strong>, and <strong><span class="highlight--red">free()</span></strong> library function to get a basic understanding of the functions.</p> <div style="overflow:auto"><table><thead><tr><th style="text-align:center">C Functions</th><th style="text-align:center">Definition</th><th style="text-align:center">Syntax</th></tr></thead><tbody><tr><td style="text-align:center"><a href="#malloc-examples" target="_blank" title="">malloc()</a></td><td style="text-align:center">It is used to allocate memory of the argument&#x27;s size (in bytes) and returns a void pointer to the allocated pointer&#x27;s first byte.</td><td style="text-align:center"><strong><span class="highlight--red">(cast-data-type *)malloc(size-in-bytes)</span></strong></td></tr><tr><td style="text-align:center"><a href="#calloc-examples" target="_blank" title="">calloc()</a></td><td style="text-align:center">It is used to allocate space as an array of elements, it also initializes all the elements with <span class="highlight--red">0</span> and returns a void pointer.</td><td style="text-align:center"><strong><span class="highlight--red">(cast-data-type *)calloc(num, size-in-bytes)</span></strong></td></tr><tr><td style="text-align:center"><a href="#free-example" target="_blank" title="">free()</a></td><td style="text-align:center">It is used to clear the allocated space (de-allocate) from the heap memory.</td><td style="text-align:center"><strong><span class="highlight--red">free(ptr)</span></strong></td></tr></tbody></table></div></section> <section class="tip"><p><strong>Note:</strong> The <strong><span class="highlight--red">malloc()</span></strong> and the <strong><span class="highlight--red">calloc()</span></strong> function returns a void pointer, so we have to typecast them into the required data types before using the allocated memory.</p></section> <section class="main"><h3 id="&quot;new&quot;-vs-&quot;malloc--&quot;-and-&quot;calloc--&quot;" level="3">&quot;new&quot; vs &quot;malloc()&quot; and &quot;calloc()&quot;</h3><p>The <strong>new</strong> operator has a similar working as <a href="https://www.scaler.com/topics/difference-between-malloc-and-calloc-in-c/" target="_blank" title="">malloc() and calloc()</a> functions because these all are used to allocate memory during the execution of a C/C++ program but, when the <strong>new</strong> operator is used with objects it invokes the constructor function of the class, while <strong><span class="highlight--red">malloc()</span></strong> and <strong><span class="highlight--red">calloc()</span></strong> doesn&#x27;t invoke the constructor function.</p><p><strong>Example C++ Program:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Output:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Explanation:</strong> We can see that, when an object <strong>dog</strong> was created using the <strong>new</strong> operator, the constructor is invoked. Also, when we have created an array of <strong>Animal</strong> class (<strong><span class="highlight--red">dogs</span></strong>) with <strong><span class="highlight--red">5</span></strong> elements, the default constructor is invoked <strong><span class="highlight--red">5</span></strong> times (constructor is invoked <strong><span class="highlight--red">6</span></strong> times in total). Whereas, when an object was created using the <strong><span class="highlight--red">malloc()</span></strong> or <strong><span class="highlight--red">calloc()</span></strong> function, the constructor function is not called.</p><h3 id="&quot;delete&quot;-vs-&quot;free--&quot;" level="3">&quot;delete&quot; vs &quot;free()&quot;</h3><p>The <strong>delete</strong> operator is also similar to the <strong><span class="highlight--red">free()</span></strong> function because both methods are used to de-allocate memory during the execution of a C/C++ program but, when the <strong>delete</strong> operator is used with objects it invokes the destructor function of the class when the object is de-allocated, while <strong><span class="highlight--red">free()</span></strong> doesn&#x27;t invoke the destructor function.</p><p><strong>Example C++ Program:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Output:</strong></p><pre><div class="code-box_snippetContainer__cJ6zK"></div></pre><p><strong>Explanation:</strong> We can see that, when an object <strong>dog</strong> was created using the <strong>new</strong> operator, the constructor is invoked. Also, we have created an object of <strong>Animal</strong> class (<strong><span class="highlight--red">cat</span></strong>) using the <strong><span class="highlight--red">malloc()</span></strong> function. When the <strong>delete</strong> operator is used with the <strong>dog</strong> object, it invokes the default destructor function. Whereas, when the <strong><span class="highlight--red">free()</span></strong> function is called with the <strong>cat</strong> object, the destructor function is not called.</p></section> <div></div> <section class="summary"><h2 id="conclusion" level="2">Conclusion</h2><ul> <li> <p>A system&#x27;s memory is one of the most important resources available to us since it can be used as both static memory and dynamic memory.</p> </li> <li> <p>Allocation and de-allocation of memory blocks during run-time is known as <strong>Dynamic Memory Allocation</strong> in C++.</p> </li> <li> <p>DMA is a very essential concept in the field of data structures as Linked Lists, Stacks, Queues, Trees, etc., requirements allocation and de-allocation of memory blocks at run-time.</p> </li> <li> <p>The <strong>new</strong> operator is used to allocate a memory block, while the <strong>delete</strong> operator is used to de-allocate a memory block.</p> </li> <li> <p>In C language, we use <strong><span class="highlight--red">malloc()</span></strong>, <strong><span class="highlight--red">calloc()</span></strong>, and <strong>free</strong> functions, while in C++ language we use <strong>new</strong> and <strong>delete</strong> operators to allocate and de-allocate memory blocks at run-time.</p> </li> </ul></section> <section class="main"><h2 id="read-more:" level="2">Read More:</h2><ul> <li><a href="https://www.scaler.com/topics/cpp/inheritance-in-cpp/" target="_blank" title="">Inheritance in C++</a>.</li> <li><a href="https://www.scaler.com/topics/cpp/data-types-in-cpp/" target="_blank" title="">Learn about Data Types in C++</a>.</li> </ul></section></div></div></div></div><div class="view_right_section__M6YCz relative p-b-m"></div></div></div><footer><div class="full-width feedback_container__imOut"><div role="button" tabindex="0" class="signin-alert-popup_signInWrapper__Kr4eW"><div class="signin-alert-popup_overLay__Xq3de"></div><div class="row flex-c feedback_feedback_container__YUVyH"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/suggestion_bulb.svg" alt="topics" width="24" height="24" loading="lazy"/><div class="feedback_description__POrxt">Got suggestions?<!-- --> <a class="Tappable-module_root__N7ll5 topics_link feedback_highlighted_text_bottom__CBT21">We would love to hear your feedback.</a></div></div></div></div><div><div class="sidebar_sidebar_ui__IJWgB hide-in-tablet feedback_feedback_content__e6Ole"><div class="feedback_form_container__0L_1Q"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/filled_bulb_pink.svg" alt="topics" width="48" height="48" loading="lazy"/><span class="feedback_feedback_form_text___aJ6l">Your feedback is important to help us improve</span><form class="p-v-10"><textarea placeholder="Your question and comment here" name="feedback" class="feedback_feedback_form__RcrvD"></textarea></form></div><div class="feedback_btn_container__PVJpo"><a class="Tappable-module_root__N7ll5 feedback_btn_effect__U_NEY"><span class="feedback_close_btn__LOmia">Close</span></a><a class="Tappable-module_root__N7ll5 Tappable-module_disabled__XhpfV topics_btn feedback_submit_btn_effect__m1pbm feedback_submit_btn__YzwTC"><span>Submit</span> <svg fill="currentColor" class="icons_icon_arrow__2GBht icons_icon_arrow__right__WUCHP m-l-5" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M5.313 16l10.688-10.688 10.688 10.688-1.938 1.875-7.438-7.438v16.25h-2.625v-16.25l-7.5 7.438z"></path></svg></a></div></div></div><div class="Footer_footer_main__jhKFJ"><div class="Footer_footer_container__0Gbr1"><div class="Footer_scaler_topics_container__NhfHg"><div class="row flex-ac Footer_scaler_topics__x_37L"><a href="https://www.scaler.com/topics/"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/logo.svg" alt="topics logo" width="53" height="40" loading="lazy"/></a><div class="Footer_separator___ExiD"></div><div class="Footer_about_scaler_topic__xVnKx"><div class="bold">A Free learning platform</div><div class="row flex-ac">made with  <img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/icon_heart.svg" alt="heart icon" width="16" height="16" loading="lazy"/>   by  <a href="https://www.scaler.com/?utm_source=topics&amp;utm_medium=footer"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/scaler_logo.svg" alt="scaler logo" width="60" height="8" loading="lazy"/></a></div></div></div><div class="row wrap flex-ac Footer_social_media_icons__Cmgt6"><a href="https://www.instagram.com/scaler_official/" target="_blank" rel="noreferrer"><div class="row Footer_social_media_bubble__AMyOI"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/instagram_footer.svg" alt="Instagram" loading="lazy"/></div></a><a href="https://www.youtube.com/c/SCALER" target="_blank" rel="noreferrer"><div class="row Footer_social_media_bubble__AMyOI"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/youtube_footer.svg" alt="Youtube" loading="lazy"/></div></a><a href="https://twitter.com/scaler_official" target="_blank" rel="noreferrer"><div class="row Footer_social_media_bubble__AMyOI"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/new_twitter.svg" alt="Twitter" loading="lazy"/></div></a><a href="https://www.facebook.com/scalerofficial" target="_blank" rel="noreferrer"><div class="row Footer_social_media_bubble__AMyOI"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/fb_footer.svg" alt="Facebook" loading="lazy"/></div></a><a href="https://www.linkedin.com/school/scalerofficial/mycompany/" target="_blank" rel="noreferrer"><div class="row Footer_social_media_bubble__AMyOI"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/linkedin_footer.svg" alt="Linkedin" loading="lazy"/></div></a><a href="https://discord.com/invite/gD2ZTC5j8K" target="_blank" rel="noreferrer"><div class="row Footer_social_media_bubble__AMyOI"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/discord_footer.svg" alt="Discord" loading="lazy"/></div></a></div></div><div class="Footer_explore_container__EfzLo"><div class="Footer_footer__column__xAs3n"><div class="Footer_footer__heading__f3vN5">Explore Scaler</div><div class="Footer_underLineClassName__gYjXL"></div><ul class="Footer_footer__contents__4EKIb"><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="https://www.scaler.com/academy/?utm_source=topics&amp;utm_medium=footer" target="_blank" rel="noreferrer">Academy</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="https://www.scaler.com/data-science-course/?utm_source=topics&amp;utm_medium=footer" target="_blank" rel="noreferrer">Data Science &amp; ML</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="https://www.scaler.com/neovarsity/?utm_source=topics&amp;utm_medium=footer" target="_blank" rel="noreferrer">Neovarsity</a></li></ul></div><div class="Footer_footer__column__xAs3n"><div class="Footer_footer__heading__f3vN5">Explore Topics</div><div class="Footer_underLineClassName__gYjXL"></div><ul class="Footer_footer__contents__4EKIb"><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="/topics/courses/">Free Online Courses</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="/topics/challenges/">Challenges</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="/topics/contests/">Contest</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="/topics/hubs/">Topics</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="/topics/articles/">Articles</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="/topics/events/">Events</a></li></ul></div><div class="Footer_footer__column__xAs3n"><div class="Footer_footer__heading__f3vN5">Resources</div><div class="Footer_underLineClassName__gYjXL"></div><ul class="Footer_footer__contents__4EKIb"><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="https://www.scaler.com/about/?utm_source=topics&amp;utm_medium=footer">About Us</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="https://www.scaler.com/blog/?utm_source=topics&amp;utm_medium=footer">Blog</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="https://www.scaler.com/careers/?utm_source=topics&amp;utm_medium=footer">Careers</a></li><li class="Footer_footer__list___R5w0"><a class="Footer_footer__link__PbMJQ" href="https://www.scaler.com/review/?utm_source=topics&amp;utm_medium=footer">Review</a></li></ul></div></div><div class="Footer_download_app_container__7I8po"><div class="row flex-ac wrap Footer_download_heading_text__0unCX"><div class="bold">Download the  </div><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/scaler_logo.svg" alt="scaler logo" width="112.5" height="15" loading="lazy"/><div class="bold">app!</div></div><div class="Footer_download_subheading_text__b2GAe">Get all scaler resources under one roof!</div><div class="Footer_download_container__ZVMHW"><div><div class="row m-b-xs"><div class="column flex-c"><div class="row flex-ac Footer_rating__85Peu">4.4<svg fill="currentColor" class="Footer_rating__star__IOBaM" version="1.1" xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 32 32"><path d="M7.569 30.625c-0.335 0-0.667-0.103-0.949-0.309-0.529-0.382-0.775-1.039-0.631-1.675l1.963-8.65-6.659-5.84c-0.489-0.427-0.676-1.104-0.475-1.724 0.201-0.618 0.747-1.056 1.395-1.115l8.811-0.8 3.485-8.153c0.257-0.599 0.843-0.986 1.492-0.986 0.651 0 1.235 0.386 1.492 0.983l3.484 8.155 8.81 0.8c0.649 0.058 1.195 0.497 1.397 1.115 0.201 0.619 0.014 1.296-0.476 1.724l-6.659 5.839 1.964 8.651c0.144 0.636-0.102 1.293-0.63 1.675-0.527 0.381-1.229 0.411-1.783 0.078l-7.598-4.541-7.598 4.543c-0.257 0.153-0.544 0.23-0.832 0.23z"></path></svg></div><div class="Footer_rating__subtext__FS9tD">1.71 K Reviews</div></div><div class="Footer_rating__separator__uK_xK"></div><div class="column flex-c"><div class="row flex-ac Footer_rating__85Peu">100K+</div><div class="Footer_rating__subtext__FS9tD">Downloads</div></div></div><div class="row"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/qr_codes/topics_footer_web.svg" alt="QR Code" width="48" height="48" class="Footer_qr_code__F2XYl" loading="lazy"/><div class="Footer_download_subsection__SvcVD"><a href="https://app.scaler.com/XBSh"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/playstore.svg" alt="Playstore Icon" width="92" height="28" class="Footer_mobile_spacer__Jt_yy" loading="lazy"/></a></div></div></div><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/app_download_phone.webp" alt="Playstore Icon" width="130" height="130" class="Footer_download_app_phone__38Crd" loading="lazy"/></div><a href="https://app.scaler.com/Yhwr"><img src="https://d1g0iq4cbcvjcd.cloudfront.net/topics/images/playstore.svg" alt="Playstore Icon" width="92" height="28" class="full-width row flex-ac Footer_mobile_spacer__Jt_yy Footer_mobile_playstore_icon__Dxy6L" loading="lazy"/></a></div></div><div class="Footer_horizontal_separator__72YMO"></div><div class="Footer_seo_container__LpX49"><div class="Footer_seo_heading__F__ls">Popular Free Certification Courses</div><div class="full-width row wrap m-t-xxs Footer_mobile_link_display__A2mzt"><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/java-beginners/" title="Free Java Course Online" class="Footer_link_title__iX4E6">Java Course for Beginners</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/cpp-beginners/" title="Free C++ Course Online" class="Footer_link_title__iX4E6">C++ Course with Certificate</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/python-for-beginners/" title="Free Python Course Online" class="Footer_link_title__iX4E6">Python Course for Beginners</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/javascript-beginners/" title="Free Javascript Course Online" class="Footer_link_title__iX4E6">Javascript Free Course for Beginners</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/python-for-data-science/" title="Free Data Science Course Online" class="Footer_link_title__iX4E6">Data Science Course for Beginners</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/dbms/" title="Free DBMS Course Online" class="Footer_link_title__iX4E6">DBMS Course</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/python-sql-data-science/" title="Free Python for Data Science Course Online" class="Footer_link_title__iX4E6">Python and SQL for Data Science Course</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/dsa-interviews-java/" title="Free DSA Java Interview Questions Online" class="Footer_link_title__iX4E6">DSA Problem Solving for Interviews</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/instagram-system-design/" title="Free Instagram Design Course Online" class="Footer_link_title__iX4E6">Instagram System Design Course</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/course/dynamic-programming/" title="Free Dynamic Programming Course Online" class="Footer_link_title__iX4E6">Dynamic Programming Course</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/courses/" title="All Free Online Courses" class="Footer_link_title__iX4E6">All Free Online Courses</a></div></div></div><div class="Footer_seo_container__LpX49"><div class="Footer_seo_heading__F__ls">Popular Tutorials</div><div class="full-width row wrap m-t-xxs Footer_mobile_link_display__A2mzt"><div class="row flex-ac"><a href="https://www.scaler.com/topics/python/" title="Python Tutorial Online" class="Footer_link_title__iX4E6">Python Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/java/" title="Java Tutorial Online" class="Footer_link_title__iX4E6">Java Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/dbms/" title="DBMS Tutorial Online" class="Footer_link_title__iX4E6">DBMS Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/javascript/" title="Javascript Tutorial Online" class="Footer_link_title__iX4E6">Javascript Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/cpp/" title="C++ Tutorial Online" class="Footer_link_title__iX4E6">C++ Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/sql/" title="SQL Tutorial Online" class="Footer_link_title__iX4E6">SQL Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/software-engineering/" title="Software Engineering Tutorial Online" class="Footer_link_title__iX4E6">Software Engineering Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/data-science/" title="Data Science Tutorial Online" class="Footer_link_title__iX4E6">Data Science Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/pandas/" title="Pandas Tutorial Online" class="Footer_link_title__iX4E6">Pandas Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/deep-learning/" title="Deep Learning Tutorial Online" class="Footer_link_title__iX4E6">Deep Learning Tutorial</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/hubs/" title="All Tutorials" class="Footer_link_title__iX4E6">All Tutorials</a></div></div></div><div class="Footer_seo_container__LpX49"><div class="Footer_seo_heading__F__ls">Compilers</div><div class="full-width row wrap m-t-xxs Footer_mobile_link_display__A2mzt"><div class="row flex-ac"><a href="https://www.scaler.com/topics/python/online-python-compiler/" title="Python Compiler Online" class="Footer_link_title__iX4E6">Python Compiler</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/java/online-java-compiler/" title="Java Compiler Online" class="Footer_link_title__iX4E6">Java Compiler</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/javascript/online-javascript-compiler/" title="Javascript Compiler Online" class="Footer_link_title__iX4E6">Javascript Compiler</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/c/online-c-compiler/" title="C Compiler Online" class="Footer_link_title__iX4E6">C Compiler</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/cpp/online-cpp-compiler/" title="C++ Compiler Online" class="Footer_link_title__iX4E6">C++ Compiler</a></div></div></div><div class="Footer_seo_container__LpX49"><div class="Footer_seo_heading__F__ls">Tools</div><div class="full-width row wrap m-t-xxs Footer_mobile_link_display__A2mzt"><div class="row flex-ac"><a href="https://www.scaler.com/topics/javascript/json-validator/" title="Json Validator Online" class="Footer_link_title__iX4E6">Json Validator</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/sql/sql-formatter/" title="SQL Formatter Online" class="Footer_link_title__iX4E6">SQL Formatter</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/tools/xml-formatter/" title="XML Formatter Online" class="Footer_link_title__iX4E6">XML Formatter</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/css/css-formatter/" title="CSS Formatter Online" class="Footer_link_title__iX4E6">CSS Formatter</a><span class="Footer_seo_separator__FOJzU"></span></div><div class="row flex-ac"><a href="https://www.scaler.com/topics/javascript/javascript-formatter/" title="JavaScript Formatter Online" class="Footer_link_title__iX4E6">JavaScript Formatter</a></div></div></div><div class="full-width column flex-c Footer_seo_container__LpX49"><div class="m-t-xxs Footer_links__29v39 Footer_copyright__YJEl8"><div>Copyright <!-- -->2025<!-- --> InterviewBit Technologies Pvt. Ltd. All Rights Reserved.</div></div><div class="row flex-ac m-t-xxs Footer_links__29v39"><a href="https://www.scaler.com/privacy/?utm_source=topics&amp;utm_medium=footer">Privacy Policy</a><div class="Footer_link_separator__rUm4Q"></div><a href="https://www.scaler.com/terms/?utm_source=topics&amp;utm_medium=footer">Terms of Use</a><div class="Footer_link_separator__rUm4Q"></div><a href="https://www.scaler.com/contact/?utm_source=topics&amp;utm_medium=footer">Contact Us</a></div></div></div></footer></main></div></div><script id="__NEXT_DATA__" type="application/json" crossorigin="anonymous">{"props":{"pageProps":{"propsReq":{"pageClass":"no-border","articleInfo":{"article":{"title":"Dynamic Memory Allocation in C++","slug":"dynamic-memory-allocation-in-cpp","published_at":"2022-12-14T00:00:00.000Z","last_updated_at":"2024-04-17T00:24:24.000Z","read_time":7,"description":"Learn about Dynamic Memory Allocation in C++","cover_image_alt":"dynamic memory allocation in c++","cover_image":"https://www.scaler.com/topics/images/dynamics-memory-allocation-in-cpp.webp","cover_image_thumbnail":"https://www.scaler.com/topics/images/dynamic-memory-allocation-in-cpp-thumbnail.webp","popular":false,"views_count":847,"words_count":1543,"quiz_id":519325,"quiz_pops":[{"test_id":907277,"order":1},{"test_id":907279,"order":2},{"test_id":907278,"order":3}],"content":"---\ntitle: Dynamic Memory Allocation in C++ - Scaler Topics\ndescription: In this article by Scaler Topics, we will see an explanation of memory management and types of memory (stack and heap) in C++ Language, read to know more.\ncategory: C++\nauthor: Abhishek Chandra\n---\n\n\n:::section{.abstract}\n\n## Overview\n\nThe process of allocating or de-allocating a block of memory during the execution of a program is called **Dynamic Memory Allocation**. The operators **new** and **delete** are utilized for dynamic memory allocation in C++ language, **new** operator is used to allocate a memory block, and **delete** operator is used to de-allocate a memory block which is allocated by using new operator.\n\n:::\n\n:::section{.main}\n\n## C++ Program Memory Management \n\nWhen we run a C++ program on our machine, it requires some space to store its instructions (statements), local variables, global variables, and various other [functions in C++](https://www.scaler.com/topics/cpp/functions-in-cpp/). This space required to run a C++ Program is known as **memory** in computers.\n\nThere are **two types of memory** in our system, **Static Memory and Dynamic Memory**.\n\n* **Static Memory:** It is a **constant space** allocated by the operating system during the **compile time** of a C++ program and it internally uses **stack** data structure to manage the static memory allocation. We can't reallocate the space consumed by the program until its execution is over.\n\n* **Dynamic Memory:** It is the memory that can be allocated or de-allocated by the operating system during the **run-time** of a C++ program. It is more efficient than static memory because we can **de-allocate and reuse** our memory during the run-time of our program.\n\nThe memory used by a C++ program can be divided further into four parts:\n\n1. Run-time Stack (Static Memory)\n2. Static Data Memory (for Global and Static Variables) \n3. Instructions / Statements (Static Memory)\n4. Heap (Dynamic Memory)\n\n![Types of Memory](https://scaler.com/topics/images/types-of-memory.webp)\n\n### The Stack memory\n\n* Our operating system **allocates a constant space** during compile-time of a C++ program, this space is known as **Stack memory**. \n* Stack memory is used to **hold functions**, different variables, and local statements that exist in the function definition. \n* Stack is a part of the static memory in our system and it constitutes the majority of our system's static memory.\n\n### The Heap Memory\n\n* **Heap memory** is also known as the **dynamic memory** in our system. It can be thought of as a large block of memory that is **expandable and shrinkable** during the execution of a program.\n* **Allocation and De-allocation of memory blocks** during the execution of a program can be done using **new** and **delete** operators in C++ (these operators are discussed later in the article).\n* Heap memory can be expanded as long as we do not exhaust the machine memory itself. It is not good from a programming perspective to completely use the machine memory to avoid errors, thus we must use the heap memory carefully.\n\n\n:::\n\n:::section{.main}\n\n## Types of Memory Allocation\n\n\n### 1. Static Memory Allocation in C++ (Compile-time Memory Allocation)\n\n* When memory is allocated at compile-time, it is referred to as **Static Memory Allocation**.\n* A fixed space is allocated for the local variables, function calls, and local statements, that **can not** be changed during the execution of the program.\n* We **can not allocate or de-allocate a memory block** once the execution of the program starts.\n* We **can't re-use** the static memory while the program is running. As a result, it is less effective.\n\n### 2. Dynamic Memory Allocation in C++ (Run-time Memory Allocation)\n\n* When memory is allocated or de-allocated during run-time, it is referred to as **Dynamic Memory Allocation** in C++.\n* A variable space is allocated that **can** be changed during the execution of the program.\n* We use dynamic/heap memory to allocate and de-allocate a block of memory during the execution of the program using **new** and **delete** operators.\n* We **can** re-use our heap memory during the run-time of our program. As a result, it is highly effective.\n\n\u003c!-- What is the main advantage of dynamic memory allocation over static memory allocation in C++?\n\nOptions:\nA) Dynamic memory allows memory size to be adjusted during runtime.\nB) Dynamic memory uses less overall memory.\nC) Dynamic memory allocation is faster.\nD) Dynamic memory can be allocated on the stack.\n\nCorrect Answer: A) Dynamic memory allows memory size to be adjusted during runtime. --\u003e\n\n:::\n\n:::section{.quiz_pop}\n:::\n\n:::section{.main}\n\n## Why Dynamic Memory Allocation?\n\nThere were some drawbacks of **stack memory or static memory allocation**, like the space allocated for the stack **can not be expanded** during the execution of a C++ program or we can't keep variables in the program till the time we want. So, to overcome these drawbacks, we use the **Dynamic Memory Allocation concepts**. \n\nDynamic Memory Allocation is also a very essential topic in the field of **data structures**, and it is utilized practically in all data structures. For example, dynamic arrays, linked lists, queues, trees, stack, etc. uses DMA to allocate and de-allocate memory blocks during the execution of a C++ program. \n\n:::\n\n\n:::section{.main}\n\n## How is it Different from Memory Allocated to Normal Variables?\n\nThe operating system uses static memory allocation for normal data-type variables and arrays, for example, **`int r;`**, **`double arr[10];`**, **`char name[20];`**, etc., the memory is automatically allocated at compile time and de-allocated when the function, block, or program finishes by the operating system. \n\nThe operating system uses dynamic memory allocation in C++ for dynamically allocated variables, for example, **`int* ptr = new int;`**, **`int* arr = new int[6];`**. Dynamically allocated memory does not get de-allocated until the program terminates. So, a programmer must de-allocate the memory, when it is no longer required. Memory leaks can occur when a programmer fails to de-allocate a dynamically allocated memory.\n\n:::\n\n\n:::section{.main}\n\n## How is Memory Allocated/De-Allocated in C++?\n\nIn C Language, before allocating or de-allocating memory dynamically (at run-time), we have to include **`\u003cstdlib.h\u003e`** header file to use the library functions like **`malloc()`**, **`calloc()`**, **`realloc()`** and **`free()`**.\n\nIn C++ Language, **new** and **delete** operators are pre-defined in the C++ Standard Library and don't require to include any library file for run-time allocation and de-allocation of memory blocks. Although we can use **`malloc()`**, **`calloc()`**, and other functions in C++ as well by adding the **`\u003cstdlib.h\u003e`** header file because of the backward compatibility of C++ with C Language. This article explains the **new** and **delete** operators of the C++ language. Visit [Dynamic Memory Allocation in C - Scaler Topics](https://www.scaler.com/topics/c/dynamic-memory-allocation-in-c/) to know more about DMA functions in C Language.\n\n:::\n\n:::section{.main}\n\n## Dynamic Memory Allocation \u0026 De-allocation Criteria\n\n### 1. Creating the Dynamic Space in Memory.\n\nDuring the dynamic memory allocation in C++, first, we have to create a dynamic space (in the heap memory). We use the **new** operator to create a dynamic space. \n\n### 2. Storing its Address in a Pointer\n\nOnce a **dynamic space** a created, we have to store the address of the **allocated space in a pointer variable** to access and modify the contents of the **memory block**.\n\n### 3. Deleting the Allocated Space\n\nOnce the user does not require the memory block, we delete the allocated space using the **delete** operator to free up the heap memory.\n\n:::\n\n\n:::section{.main}\n\n## The \"new\" operator in C++\n\nThe **new** operator in C++ is used to **dynamically allocate a block of memory and store its address** in a pointer variable during the execution of a C++ program if enough memory is available in the system.\n\n### Syntax for \"new\" operator:\n\n```cpp\ndata_type* ptr_var = new data_type;\n```\n\n* **`ptr_var`** is a pointer, which stores the address of the type **`data_type`**. \n* Any pre-defined data types, like **`int`**, **`char`**, etc., or other user-defined data types, like classes, can be used as the **`data_type`** with the **new** operator.\n\n### Example C++ Program:\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=2f1c6a4514666588e44f\n// how to allocate memory using the new operator example\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() \n{\n // dynamically allocating an integer memory block\n int* ptr = new int;\n\n // storing a value at the memory pointed by ptr\n *ptr = 12;\n\n cout \u003c\u003c \"Value at memory pointed by ptr= \" \u003c\u003c *ptr;\n\n return 0;\n}\n```\n\n**Output:**\n\n```plaintext\nValue at memory pointed by ptr= 12\n```\n\n**Explanation:** \n\n* A memory block is allocated using the **new** operator and the address of the memory block has been stored in the **`ptr`** pointer. \n* (**`*ptr`**) represents the value at the allocated memory location. We have assigned **`12`** in the memory using **`*ptr = 12`** expression.\n\n### Initializing Dynamic Memory\n\n**Syntax:**\n\n```cpp\ndata_type* ptr_var = new data-type(value);\n```\n\n\n**Example C++ program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=8c718e57ddbf66344dc3\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() \n{\n // dynamically allocating an integer memory block\n // with 12 as its initial value\n int* ptr = new int(12);\n\n cout \u003c\u003c \"Value at memory pointed by ptr= \" \u003c\u003c *ptr;\n\n return 0;\n}\n```\n\n**Output:**\n\n```plaintext\nValue at memory pointed by ptr= 12\n```\n\n### What Happens if the System's Memory Runs out During the Execution of the Program?\n\nWhen there is insufficient memory in the heap segment during the run-time of a C++ program, the new request for allocation fails by throwing an exception of type **`std::bad alloc`**. It can be avoided using a **nothrow** argument with the **new** operator. When we use **nothrow** with **new**, it returns a **NULL** pointer. So, the pointer variable should be checked that is formed by **new** before utilizing it in a program.\n\n**Example:**\n\n```cpp\nint* ptr = new(nothrow) int;\n\nif (ptr == NULL)\n{\n cout \u003c\u003c \"Allocation Failed!\\n\";\n}\n```\n\n:::\n\n\n:::section{.main}\n\n## The \"delete\" Operator in C++\n\nThe **delete** operator is used to de-allocate the block of memory, which is dynamically allocated using the **new** operator. Since, a programmer must de-allocate a block of memory, once it is not required in the program. So, we have to use the **delete** operator to avoid memory leaks and program crash errors, which occur due to the exhaustion of the system's memory. \n\n### Syntax:\n\nSyntax to delete a single block of memory:\n\n```cpp\ndelete ptr_var;\n```\n\nSyntax to delete an array of memory:\n\n```cpp\ndelete [] ptr_var;\n```\n\n\n### Example C++ Program:\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=c1eef4ca83c94a024b75\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nint main() \n{\n // allocating a new int stars variable using new\n int* stars = new int;\n *stars = 5000;\n\n cout\u003c\u003c\"Visible stars in the sky: \"\u003c\u003c*stars;\n\n // stars memory deallocated using the delete operator\n delete stars;\n\n cout\u003c\u003c\"\\nGarbage value: \"\u003c\u003c*stars;\n\n stars = NULL;\n\n return 0;\n}\n```\n\n\n**Output:**\n\n```plaintext\nVisible stars in the sky: 5000\nGarbage value: 1491762488\n```\n\n(output garbage value is compiler dependent and will be different at each run)\n\n\n**Explanation:**\n\n* A memory block for the **stars** pointer is allocated using the **new** operator and the address of the memory block has been stored in the **stars** pointer. \n* We have used the **delete** operator to de-allocate the memory pointed by the **stars** pointer, as it is no longer required in our program.\n* The memory is de-allocated but the **stars** pointer is still pointing to some garbage location in the memory. So, it will show **garbage value** if printed on the output screen. We have assigned **NULL** to the **stars** pointer in the end to avoid the situation of a [dangling pointer](https://www.scaler.com/topics/c/dangling-pointer-in-c/).\n\n**Image Explanation:**\n![Dynamic Memory Allocation in C++](https://scaler.com/topics/images/dynamic-memory-allocation-in-cpp.webp)\n\n \n\u003c!-- Which statement is true about the new operator in C++?\n\nOptions:\nA) It can only allocate memory for integers.\nB) It automatically deallocates memory when it's no longer needed.\nC) It initializes the memory block to zero.\nD) It can throw an exception if memory allocation fails.\n\nCorrect Answer: D) It can throw an exception if memory allocation fails --\u003e\n:::\n\n:::section{.quiz_pop}\n:::\n\n:::section{.main}\n\n## Dynamic Memory Allocation in C++ for Arrays\n\n### Allocating a Block of Memory Using the \"new\" Operator\n\nThe **new** operator can also be used to allocate a block of memory (an array) of any **`data_type`**.\n\n**Syntax:**\n\n```cpp\ndata_type* ptr_var = new data_type[size_of_the_array];\n```\n\n**Example**\n\n```cpp\nchar* name = new char[10];\n```\n\n\n\n### Standard Array Declaration vs Using the \"new\" Operator\n\nThe most significant distinction between **standard arrays and a dynamically allocated array** is that standard arrays are de-allocated by the [**online C++ compiler**](https://www.scaler.com/topics/cpp/online-cpp-compiler/) when the function execution finishes or it goes out of scope. While with dynamically allocated arrays, arrays always remain in the memory until either the programmer **de-allocates** them or the program execution finishes.\n\n**Syntax for normal array declaration:**\n\n```cpp\nint arr[5];\n```\n\n**Syntax for dynamically allocated array:**\n\n```cpp\nint* arr = new int[5];\n```\n\n\n\n**Example C++ Program with `new` operator:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=5706cdd454d80da2aa17\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nint main() \n{\n\t// dynamically allocating an integer array of size 5 using new operator \n\tint* arr = new int[5];\n\n\tcout \u003c\u003c \"Enter 5 values in the array: \";\n\n\t// taking 5 values as an input from the user\n\tfor(int i = 0; i \u003c 5; i++)\n\t{\n\t\tcin \u003e\u003e arr[i];\n\t}\t\n\n\t// displaying the array elements in the output\n\tcout \u003c\u003c \"\\nArray elements: \";\n\tfor(int i = 0; i \u003c 5; i++)\n\t{\n\t\tcout \u003c\u003c arr[i] \u003c\u003c \" \";\n\t}\n\n\t// dynamically deallocating the array using delete operator\n\tdelete [] arr;\n\n\t// garbage values will be displayed as \n\t// the pointer will point to some deallocated locations\n\tcout \u003c\u003c \"\\nGarbage array values after deallocation of array memory: \";\n\tfor(int i = 0; i \u003c 5; i++)\n\t{\n\t\tcout \u003c\u003c arr[i] \u003c\u003c \" \";\n\t}\n\n\treturn 0;\n}\n```\n\n**Custom Input:**\n```cpp\nEnter 5 values in the array: 1 2 3 4 5\n```\n\n**Output:**\n\n```plaintext\nArray elements: 1 2 3 4 5 \nGarbage array values after deallocation of array memory: -1544938184 32704 -1544938184 32704 5 \n```\n\n(output garbage values are compiler dependent and different at each run)\n\n**Explanation:** \n\n- We have created a dynamically allocated array using the **new** operator. \n- Then, we have taken input for the array elements from the user and printed the array elements.\n- With the use of the **delete** operator on the array pointer **`arr`**, we have de-allocated the array memory. Now, the array location will contain **garbage values** as seen in the output.\n\n:::\n\n:::section{.main}\n\n## Dynamic Memory Allocation in C++ for Objects\n\nWe can dynamically allocate memory for objects also. When we create an object of a class, a constructor function is invoked. Constructor is a member function of a class that is used to initialize the object. Also, when the object goes out of scope or gets **de-allocated**, a **destructor** function is invoked. Destructor is also a **class member function** that helps in knowing when the object's memory gets **deleted**.\n\nWe use pointers once more for allocating memory to objects.\n\n**Example C++ Program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=996952e543cc14e13181\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Animal \n{\n public:\n Animal() { \n cout \u003c\u003c \"Animal class constructor invoked!\" \u003c\u003cendl; \n }\n ~Animal() { \n cout \u003c\u003c \"Animal class destructor invoked!\" \u003c\u003cendl; \n }\n};\n\nint main() \n{\n // memory allocated for dog object of type Animal\n // constructor will be invoked\n Animal* dog = new Animal; \n\n // memory deallocated for dog object of type Animal\n // destructor will be invoked\n delete dog; \n\n return 0;\n}\n```\n\n**Output:**\n\n```plaintext\nAnimal class constructor invoked!\nAnimal class destructor invoked!\n```\n\n**Explanation:** We have created a class **Animal** with [constructor and destructor](https://www.scaler.com/topics/cpp/constructor-and-destructor-in-cpp/) member functions. In the **`main()`** function, we have created a **dog** object of class **Animal** using the **new** operator, which invokes the constructor function of the **Animal** class. When we have used the **delete** operator to de-allocate the **dog** object memory, the destructor function is invoked.\n\n:::\n\n:::section{.main}\n\n## Comparison with \"malloc()\", \"calloc()\", and \"free()\" Functions of C.\n\nFirst, let's see the small definitions of **`malloc()`**, **`calloc()`**, and **`free()`** library function to get a basic understanding of the functions.\n\n| C Functions | Definition| Syntax |\n| :------------: | :-------: | :-----------: |\n| [malloc()](#malloc-examples) | It is used to allocate memory of the argument's size (in bytes) and returns a void pointer to the allocated pointer's first byte.| **`(cast-data-type *)malloc(size-in-bytes)`** |\n| [calloc()](#calloc-examples) | It is used to allocate space as an array of elements, it also initializes all the elements with `0` and returns a void pointer.| **`(cast-data-type *)calloc(num, size-in-bytes)`** |\n| [free()](#free-example) | It is used to clear the allocated space (de-allocate) from the heap memory.| **`free(ptr)`** |\n:::\n:::section{.tip}\n\n**Note:** The **`malloc()`** and the **`calloc()`** function returns a void pointer, so we have to typecast them into the required data types before using the allocated memory.\n:::\n:::section{.main}\n### \"new\" vs \"malloc()\" and \"calloc()\"\n\nThe **new** operator has a similar working as [malloc() and calloc()](https://www.scaler.com/topics/difference-between-malloc-and-calloc-in-c/) functions because these all are used to allocate memory during the execution of a C/C++ program but, when the **new** operator is used with objects it invokes the constructor function of the class, while **`malloc()`** and **`calloc()`** doesn't invoke the constructor function.\n\n**Example C++ Program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=963d80336dc2f07ad348\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nclass Animal \n{\n public:\n Animal() { \n cout \u003c\u003c \"Animal class constructor invoked!\" \u003c\u003cendl; \n }\n ~Animal() { \n cout \u003c\u003c \"Animal class destructor invoked!\" \u003c\u003cendl; \n }\n};\n\nint main() \n{\n\t// memory allocated for dog object of type Animal using the new operator\n\t// here, the constructor will be called 1 time.\n\tAnimal* dog = new(nothrow) Animal; \n\n\t// 5 blocks of memory allocated for object dogs using new\n\t// here, the constructor will be called 5 times.\n\tAnimal* dogs = new(nothrow) Animal[5];\n\n\t// memory allocated for cat object of type Animal using the malloc function,\n\t// constructor will not be called.\n\tAnimal* cat = (Animal*)malloc(sizeof(Animal));\n\n\t// 5 blocks of memory allocated for object dogs using calloc function,\n\t// constructor will not be called.\n\tAnimal* cats = (Animal*)calloc(5, sizeof(Animal));\n\n\treturn 0;\n}\n```\n\n**Output:**\n\n```plaintext\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\n```\n\n**Explanation:** We can see that, when an object **dog** was created using the **new** operator, the constructor is invoked. Also, when we have created an array of **Animal** class (**`dogs`**) with **`5`** elements, the default constructor is invoked **`5`** times (constructor is invoked **`6`** times in total). Whereas, when an object was created using the **`malloc()`** or **`calloc()`** function, the constructor function is not called.\n\n\n### \"delete\" vs \"free()\"\n\nThe **delete** operator is also similar to the **`free()`** function because both methods are used to de-allocate memory during the execution of a C/C++ program but, when the **delete** operator is used with objects it invokes the destructor function of the class when the object is de-allocated, while **`free()`** doesn't invoke the destructor function.\n\n**Example C++ Program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=12d6b30f4568be996ca9\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nclass Animal \n{\n public:\n Animal() { \n cout \u003c\u003c \"Animal class constructor invoked!\" \u003c\u003cendl; \n }\n ~Animal() { \n cout \u003c\u003c \"Animal class destructor invoked!\" \u003c\u003cendl; \n }\n};\n\nint main() \n{\n\t// memory allocated for dog object of type Animal using the new operator\n\t// here, the constructor will be called 1 time.\n\tAnimal* dog = new(nothrow) Animal; \n\n\t// memory allocated for cat object of type Animal using the malloc function,\n\t// constructor will not be called.\n\tAnimal* cat = (Animal*)malloc(sizeof(Animal));\n\n\t// deallocates the memory for dog object using delete operator,\n\t// destructor will be called.\n\tdelete dog;\n\n\t// deallocates the memory for cat object using free funtion but,\n\t// destructor will not be called\n\tfree(cat);\n\n\treturn 0;\n}\n```\n\n**Output:**\n\n```plaintext\nAnimal class constructor invoked!\nAnimal class destructor invoked!\n```\n\n**Explanation:** We can see that, when an object **dog** was created using the **new** operator, the constructor is invoked. Also, we have created an object of **Animal** class (**`cat`**) using the **`malloc()`** function. When the **delete** operator is used with the **dog** object, it invokes the default destructor function. Whereas, when the **`free()`** function is called with the **cat** object, the destructor function is not called.\n\n\u003c!-- Why should the delete operator be used instead of free() in C++ when dealing with objects?\n\nOptions:\nA) delete automatically calls the destructor, whereas free() does not.\nB) free() can allocate memory, but delete cannot.\nC) delete uses less memory than free().\nD) free() is faster than delete.\n\nCorrect Answer: A) delete automatically calls the destructor, whereas free() does not. --\u003e\n\n:::\n\n:::section{.quiz_pop}\n::: \n\n:::section{.summary}\n\n## Conclusion\n- A system's memory is one of the most important resources available to us since it can be used as both static memory and dynamic memory. \n- Allocation and de-allocation of memory blocks during run-time is known as **Dynamic Memory Allocation** in C++.\n- DMA is a very essential concept in the field of data structures as Linked Lists, Stacks, Queues, Trees, etc., requirements allocation and de-allocation of memory blocks at run-time.\n- The **new** operator is used to allocate a memory block, while the **delete** operator is used to de-allocate a memory block.\n- In C language, we use **`malloc()`**, **`calloc()`**, and **free** functions, while in C++ language we use **new** and **delete** operators to allocate and de-allocate memory blocks at run-time. \n\n\n \n:::\n:::section{.main}\n## Read More:\n- [Inheritance in C++](https://www.scaler.com/topics/cpp/inheritance-in-cpp/).\n- [Learn about Data Types in C++](https://www.scaler.com/topics/cpp/data-types-in-cpp/).","course_video_data":[],"collaborators":{"authors":[{"name":"Abhishek Chandra","slug":"be19d80eba53","email":"1ac23456789@gmail.com","image":"https://lh3.googleusercontent.com/a-/ACNPEu9R2U96t1_I8R2LHopumh5WPRIBtvEDc_P5RKBLPE8=s96-c","linkedin_profile":"https://www.linkedin.com/in/abhishek-chandra1/","company":"Accenture","designation":"Technical Writer","validated_at":"2024-02-22T13:23:29.000Z","topics_slug":"abhishek-chandra","about":"Meet Abhishek Chandra, a Technical Content Writer at Scaler, dedicated to crafting insightful articles on C, C++, Java, and JavaScript. With a passion for programming languages, Abhishek brings a wealth of knowledge to simplify complex concepts, making them accessible to diverse audiences.","github_profile":null,"twitter_profile":null,"headline":"Technical Content Writer at Scaler, writing articles based on C, C++, Java, and JavaScript Language."}],"co_authors":[],"reviewers":[],"fact_checkers":[]},"tags":[{"title":"C++","slug":"cpp"}],"programs":["academy","programming_languages"]},"treeMap":{"-1":{"slug":"-1","title":"","read":false,"current":false,"isExpanded":false,"link":"","children":["module_the-history-of-c","module_mechanism-of-creating-a-programme-in-c","module_programme-structure-and-best-practices-in-c","module_data-dealing-in-c","module_control-flow-in-c","module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44","module_pointers-and-references-in-c","module_compound-data-types-in-c","module_storage-classes-in-c","module_object-oriented-programming","module_advance-concepts-of-oops","module_stl","module_miscellaneous"],"parent":"","prev":"","next":"","image":null},"module_the-history-of-c":{"slug":"module_the-history-of-c","title":"The History of C++","read":false,"current":false,"isExpanded":false,"link":"","children":["origin-and-philosophy-of-cpp","difference-between-c-and-cplusplus"],"parent":"-1","prev":"","next":"","image":null},"origin-and-philosophy-of-cpp":{"slug":"origin-and-philosophy-of-cpp","title":"C++ Origin and philosophy - History of C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/origin-and-philosophy-of-cpp/","children":[],"parent":"module_the-history-of-c","prev":"","next":"difference-between-c-and-cplusplus","image":null},"difference-between-c-and-cplusplus":{"slug":"difference-between-c-and-cplusplus","title":"Difference Between C and C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/difference-between-c-and-cplusplus/","children":[],"parent":"module_the-history-of-c","prev":"origin-and-philosophy-of-cpp","next":"cpp-environment-setup","image":null},"module_mechanism-of-creating-a-programme-in-c":{"slug":"module_mechanism-of-creating-a-programme-in-c","title":"Mechanism of Creating a Programme in C++ ","read":false,"current":false,"isExpanded":false,"link":"","children":["cpp-environment-setup"],"parent":"-1","prev":"","next":"","image":null},"cpp-environment-setup":{"slug":"cpp-environment-setup","title":"C++ Environment Setup","read":false,"current":false,"isExpanded":false,"link":"/cpp/cpp-environment-setup/","children":[],"parent":"module_mechanism-of-creating-a-programme-in-c","prev":"difference-between-c-and-cplusplus","next":"comments-in-cpp","image":null},"module_programme-structure-and-best-practices-in-c":{"slug":"module_programme-structure-and-best-practices-in-c","title":"Programme Structure and Best Practices in C++","read":false,"current":false,"isExpanded":false,"link":"","children":["comments-in-cpp","cpp-header-files","namespace-in-cpp","cpp-coding-standards","statements-in-cpp"],"parent":"-1","prev":"","next":"","image":null},"comments-in-cpp":{"slug":"comments-in-cpp","title":"C++ Comments and C-style Comment in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/comments-in-cpp/","children":[],"parent":"module_programme-structure-and-best-practices-in-c","prev":"cpp-environment-setup","next":"cpp-header-files","image":null},"cpp-header-files":{"slug":"cpp-header-files","title":"C++ Header Files","read":false,"current":false,"isExpanded":false,"link":"/cpp/cpp-header-files/","children":[],"parent":"module_programme-structure-and-best-practices-in-c","prev":"comments-in-cpp","next":"namespace-in-cpp","image":null},"namespace-in-cpp":{"slug":"namespace-in-cpp","title":"Namespaces in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/namespace-in-cpp/","children":[],"parent":"module_programme-structure-and-best-practices-in-c","prev":"cpp-header-files","next":"cpp-coding-standards","image":null},"cpp-coding-standards":{"slug":"cpp-coding-standards","title":"C++ Coding Standards","read":false,"current":false,"isExpanded":false,"link":"/cpp/cpp-coding-standards/","children":[],"parent":"module_programme-structure-and-best-practices-in-c","prev":"namespace-in-cpp","next":"statements-in-cpp","image":null},"statements-in-cpp":{"slug":"statements-in-cpp","title":"Statements in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/statements-in-cpp/","children":[],"parent":"module_control-flow-in-c","prev":"expressions-in-cpp","next":"loop-in-cpp","image":null},"module_data-dealing-in-c":{"slug":"module_data-dealing-in-c","title":"Data Dealing in C++","read":false,"current":false,"isExpanded":false,"link":"","children":["data-types-in-cpp","modifiers-in-cpp","constants-in-cpp","keywords-in-cpp","variables-in-c-plus-plus","auto-in-cpp","difference-between-unicode-and-ascii","binary-representation-of-a-number","type-conversion-in-cpp","operators-in-cpp","expressions-in-cpp"],"parent":"-1","prev":"","next":"","image":null},"data-types-in-cpp":{"slug":"data-types-in-cpp","title":"Data Types in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/data-types-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"statements-in-cpp","next":"modifiers-in-cpp","image":null},"modifiers-in-cpp":{"slug":"modifiers-in-cpp","title":"Modifiers in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/modifiers-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"data-types-in-cpp","next":"constants-in-cpp","image":null},"constants-in-cpp":{"slug":"constants-in-cpp","title":"Constants in c++","read":false,"current":false,"isExpanded":false,"link":"/cpp/constants-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"modifiers-in-cpp","next":"keywords-in-cpp","image":null},"keywords-in-cpp":{"slug":"keywords-in-cpp","title":"Keywords in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/keywords-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"constants-in-cpp","next":"variables-in-c-plus-plus","image":null},"variables-in-c-plus-plus":{"slug":"variables-in-c-plus-plus","title":"Variables in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/variables-in-c-plus-plus/","children":[],"parent":"module_data-dealing-in-c","prev":"keywords-in-cpp","next":"auto-in-cpp","image":null},"auto-in-cpp":{"slug":"auto-in-cpp","title":"Auto in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/auto-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"variables-in-c-plus-plus","next":"difference-between-unicode-and-ascii","image":null},"difference-between-unicode-and-ascii":{"slug":"difference-between-unicode-and-ascii","title":"Difference Between UNICODE and ASCII","read":false,"current":false,"isExpanded":false,"link":"/cpp/difference-between-unicode-and-ascii/","children":[],"parent":"module_data-dealing-in-c","prev":"auto-in-cpp","next":"binary-representation-of-a-number","image":null},"binary-representation-of-a-number":{"slug":"binary-representation-of-a-number","title":"Binary Representation of A Given Number in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/binary-representation-of-a-number/","children":[],"parent":"module_data-dealing-in-c","prev":"difference-between-unicode-and-ascii","next":"type-conversion-in-cpp","image":null},"type-conversion-in-cpp":{"slug":"type-conversion-in-cpp","title":"Type Conversion in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/type-conversion-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"binary-representation-of-a-number","next":"operators-in-cpp","image":null},"operators-in-cpp":{"slug":"operators-in-cpp","title":"Operators in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/operators-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"type-conversion-in-cpp","next":"expressions-in-cpp","image":null},"expressions-in-cpp":{"slug":"expressions-in-cpp","title":"Expressions in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/expressions-in-cpp/","children":[],"parent":"module_data-dealing-in-c","prev":"operators-in-cpp","next":"statements-in-cpp","image":null},"module_control-flow-in-c":{"slug":"module_control-flow-in-c","title":"Control Flow in C++","read":false,"current":false,"isExpanded":false,"link":"","children":["statements-in-cpp","loop-in-cpp","jump-statement-in-cpp"],"parent":"-1","prev":"","next":"","image":null},"loop-in-cpp":{"slug":"loop-in-cpp","title":"Loop in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/loop-in-cpp/","children":[],"parent":"module_control-flow-in-c","prev":"statements-in-cpp","next":"jump-statement-in-cpp","image":null},"jump-statement-in-cpp":{"slug":"jump-statement-in-cpp","title":"Jump Statement in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/jump-statement-in-cpp/","children":[],"parent":"module_control-flow-in-c","prev":"loop-in-cpp","next":"functions-in-cpp","image":null},"module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44":{"slug":"module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44","title":"Functions in C++","read":false,"current":false,"isExpanded":false,"link":"","children":["functions-in-cpp","library-functions-in-cpp","recursion-in-cpp","cpp-preprocessor-directives","adventures-in-functions"],"parent":"-1","prev":"","next":"","image":null},"functions-in-cpp":{"slug":"functions-in-cpp","title":"Functions in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/functions-in-cpp/","children":[],"parent":"module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44","prev":"jump-statement-in-cpp","next":"library-functions-in-cpp","image":null},"library-functions-in-cpp":{"slug":"library-functions-in-cpp","title":"Library Functions in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/library-functions-in-cpp/","children":[],"parent":"module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44","prev":"functions-in-cpp","next":"recursion-in-cpp","image":null},"recursion-in-cpp":{"slug":"recursion-in-cpp","title":"C++ Recursion","read":false,"current":false,"isExpanded":false,"link":"/cpp/recursion-in-cpp/","children":[],"parent":"module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44","prev":"library-functions-in-cpp","next":"cpp-preprocessor-directives","image":null},"cpp-preprocessor-directives":{"slug":"cpp-preprocessor-directives","title":"Preprocessor Directives in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/cpp-preprocessor-directives/","children":[],"parent":"module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44","prev":"recursion-in-cpp","next":"adventures-in-functions","image":null},"adventures-in-functions":{"slug":"adventures-in-functions","title":"More about functions in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/adventures-in-functions/","children":[],"parent":"module_functions-in-c-efe9e6ef-9a1a-4444-b747-1171ed867c44","prev":"cpp-preprocessor-directives","next":"pointers-in-cpp","image":null},"module_pointers-and-references-in-c":{"slug":"module_pointers-and-references-in-c","title":"Pointers and References in C++","read":false,"current":false,"isExpanded":false,"link":"","children":["pointers-in-cpp","pointers-vs-references-in-cplusplus","opaque-pointer-in-cpp","smart-pointers-in-cpp","pointer-to-pointer-cpp","functions-with-variable-number-of-arguments-in-cpp","complex-declarations-in-cpp","function-pointer-cpp"],"parent":"-1","prev":"","next":"","image":null},"pointers-in-cpp":{"slug":"pointers-in-cpp","title":"Pointers in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/pointers-in-cpp/","children":[],"parent":"module_pointers-and-references-in-c","prev":"adventures-in-functions","next":"pointers-vs-references-in-cplusplus","image":null},"pointers-vs-references-in-cplusplus":{"slug":"pointers-vs-references-in-cplusplus","title":"Pointers vs References in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/pointers-vs-references-in-cplusplus/","children":[],"parent":"module_pointers-and-references-in-c","prev":"pointers-in-cpp","next":"opaque-pointer-in-cpp","image":null},"opaque-pointer-in-cpp":{"slug":"opaque-pointer-in-cpp","title":"Opaque Pointer in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/opaque-pointer-in-cpp/","children":[],"parent":"module_pointers-and-references-in-c","prev":"pointers-vs-references-in-cplusplus","next":"smart-pointers-in-cpp","image":null},"smart-pointers-in-cpp":{"slug":"smart-pointers-in-cpp","title":"Smart Pointers in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/smart-pointers-in-cpp/","children":[],"parent":"module_pointers-and-references-in-c","prev":"opaque-pointer-in-cpp","next":"pointer-to-pointer-cpp","image":null},"pointer-to-pointer-cpp":{"slug":"pointer-to-pointer-cpp","title":"Pointers to Pointers in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/pointer-to-pointer-cpp/","children":[],"parent":"module_pointers-and-references-in-c","prev":"smart-pointers-in-cpp","next":"functions-with-variable-number-of-arguments-in-cpp","image":null},"functions-with-variable-number-of-arguments-in-cpp":{"slug":"functions-with-variable-number-of-arguments-in-cpp","title":"Functions with Variable Number of Arguments in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/functions-with-variable-number-of-arguments-in-cpp/","children":[],"parent":"module_pointers-and-references-in-c","prev":"pointer-to-pointer-cpp","next":"complex-declarations-in-cpp","image":null},"complex-declarations-in-cpp":{"slug":"complex-declarations-in-cpp","title":"Complex Declarations in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/complex-declarations-in-cpp/","children":[],"parent":"module_pointers-and-references-in-c","prev":"functions-with-variable-number-of-arguments-in-cpp","next":"function-pointer-cpp","image":null},"function-pointer-cpp":{"slug":"function-pointer-cpp","title":"Pointers to Functions in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/function-pointer-cpp/","children":[],"parent":"module_pointers-and-references-in-c","prev":"complex-declarations-in-cpp","next":"array-in-cpp","image":null},"module_compound-data-types-in-c":{"slug":"module_compound-data-types-in-c","title":"Compound Data Types in C++","read":false,"current":false,"isExpanded":false,"link":"","children":["array-in-cpp","strings-in-cpp","union-and-enum-in-Cpp"],"parent":"-1","prev":"","next":"","image":null},"array-in-cpp":{"slug":"array-in-cpp","title":"Array in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/array-in-cpp/","children":[],"parent":"module_compound-data-types-in-c","prev":"function-pointer-cpp","next":"strings-in-cpp","image":null},"strings-in-cpp":{"slug":"strings-in-cpp","title":"Strings in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/strings-in-cpp/","children":[],"parent":"module_compound-data-types-in-c","prev":"array-in-cpp","next":"union-and-enum-in-Cpp","image":null},"union-and-enum-in-Cpp":{"slug":"union-and-enum-in-Cpp","title":"Union and Enum in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/union-and-enum-in-Cpp/","children":[],"parent":"module_compound-data-types-in-c","prev":"strings-in-cpp","next":"storage-classes-in-cpp","image":null},"module_storage-classes-in-c":{"slug":"module_storage-classes-in-c","title":"Storage Classes in C++","read":false,"current":false,"isExpanded":false,"link":"","children":["storage-classes-in-cpp"],"parent":"-1","prev":"","next":"","image":null},"storage-classes-in-cpp":{"slug":"storage-classes-in-cpp","title":"Storage Classes in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/storage-classes-in-cpp/","children":[],"parent":"module_storage-classes-in-c","prev":"union-and-enum-in-Cpp","next":"procedural-programming","image":null},"module_object-oriented-programming":{"slug":"module_object-oriented-programming","title":"Object Oriented Programming","read":false,"current":false,"isExpanded":false,"link":"","children":["procedural-programming","class-and-object-in-cpp","constructor-and-destructor-in-cpp","abstraction-in-cpp","generic-programming-in-cpp","this-pointer-in-cpp","static-member-in-cpp"],"parent":"-1","prev":"","next":"","image":null},"procedural-programming":{"slug":"procedural-programming","title":"Procedural Programming and Object Oriented Programming in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/procedural-programming/","children":[],"parent":"module_object-oriented-programming","prev":"storage-classes-in-cpp","next":"class-and-object-in-cpp","image":null},"class-and-object-in-cpp":{"slug":"class-and-object-in-cpp","title":"Classes and Objects in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/class-and-object-in-cpp/","children":[],"parent":"module_object-oriented-programming","prev":"procedural-programming","next":"constructor-and-destructor-in-cpp","image":null},"constructor-and-destructor-in-cpp":{"slug":"constructor-and-destructor-in-cpp","title":"Constructor and Destructor in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/constructor-and-destructor-in-cpp/","children":[],"parent":"module_object-oriented-programming","prev":"class-and-object-in-cpp","next":"abstraction-in-cpp","image":null},"abstraction-in-cpp":{"slug":"abstraction-in-cpp","title":"Abstraction in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/abstraction-in-cpp/","children":[],"parent":"module_object-oriented-programming","prev":"constructor-and-destructor-in-cpp","next":"generic-programming-in-cpp","image":null},"generic-programming-in-cpp":{"slug":"generic-programming-in-cpp","title":"Generic Programming in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/generic-programming-in-cpp/","children":[],"parent":"module_object-oriented-programming","prev":"abstraction-in-cpp","next":"this-pointer-in-cpp","image":null},"this-pointer-in-cpp":{"slug":"this-pointer-in-cpp","title":"‘this’ Pointer in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/this-pointer-in-cpp/","children":[],"parent":"module_object-oriented-programming","prev":"generic-programming-in-cpp","next":"static-member-in-cpp","image":null},"static-member-in-cpp":{"slug":"static-member-in-cpp","title":"Static Member in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/static-member-in-cpp/","children":[],"parent":"module_object-oriented-programming","prev":"this-pointer-in-cpp","next":"operator-overloading-in-cpp","image":null},"module_advance-concepts-of-oops":{"slug":"module_advance-concepts-of-oops","title":"Advance Concepts of OOPS","read":false,"current":true,"isExpanded":true,"link":"","children":["operator-overloading-in-cpp","friend-function-in-cpp","dynamic-memory-allocation-in-cpp","dynamic-member","inheritance-in-cpp","type-conversions-in-class-hierarchies","polymorphism-in-cpp","abstract-class-in-cpp","multiple-inheritance-in-cpp","templates-in-cpp","exception-handling-in-cpp","file-handling-in-cpp"],"parent":"-1","prev":"","next":"","image":null},"operator-overloading-in-cpp":{"slug":"operator-overloading-in-cpp","title":"Operator Overloading in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/operator-overloading-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"static-member-in-cpp","next":"friend-function-in-cpp","image":null},"friend-function-in-cpp":{"slug":"friend-function-in-cpp","title":"Friend Function in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/friend-function-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"operator-overloading-in-cpp","next":"dynamic-memory-allocation-in-cpp","image":null},"dynamic-memory-allocation-in-cpp":{"slug":"dynamic-memory-allocation-in-cpp","title":"Dynamic Memory Allocation in C++","read":false,"current":true,"isExpanded":true,"link":"/cpp/dynamic-memory-allocation-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"friend-function-in-cpp","next":"dynamic-member","image":null},"dynamic-member":{"slug":"dynamic-member","title":"Dynamic Members","read":false,"current":false,"isExpanded":false,"link":"/cpp/dynamic-member/","children":[],"parent":"module_advance-concepts-of-oops","prev":"dynamic-memory-allocation-in-cpp","next":"inheritance-in-cpp","image":null},"inheritance-in-cpp":{"slug":"inheritance-in-cpp","title":"Inheritance in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/inheritance-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"dynamic-member","next":"type-conversions-in-class-hierarchies","image":null},"type-conversions-in-class-hierarchies":{"slug":"type-conversions-in-class-hierarchies","title":"Type Conversions in Class Hierarchies","read":false,"current":false,"isExpanded":false,"link":"/cpp/type-conversions-in-class-hierarchies/","children":[],"parent":"module_advance-concepts-of-oops","prev":"inheritance-in-cpp","next":"polymorphism-in-cpp","image":null},"polymorphism-in-cpp":{"slug":"polymorphism-in-cpp","title":"Polymorphism in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/polymorphism-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"type-conversions-in-class-hierarchies","next":"abstract-class-in-cpp","image":null},"abstract-class-in-cpp":{"slug":"abstract-class-in-cpp","title":"Abstract Class in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/abstract-class-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"polymorphism-in-cpp","next":"multiple-inheritance-in-cpp","image":null},"multiple-inheritance-in-cpp":{"slug":"multiple-inheritance-in-cpp","title":"Multiple Inheritance in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/multiple-inheritance-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"abstract-class-in-cpp","next":"templates-in-cpp","image":null},"templates-in-cpp":{"slug":"templates-in-cpp","title":"Templates in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/templates-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"multiple-inheritance-in-cpp","next":"exception-handling-in-cpp","image":null},"exception-handling-in-cpp":{"slug":"exception-handling-in-cpp","title":"Exception Handling in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/exception-handling-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"templates-in-cpp","next":"file-handling-in-cpp","image":null},"file-handling-in-cpp":{"slug":"file-handling-in-cpp","title":"File Handling in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/file-handling-in-cpp/","children":[],"parent":"module_advance-concepts-of-oops","prev":"exception-handling-in-cpp","next":"map-in-cpp","image":null},"module_stl":{"slug":"module_stl","title":"STL","read":false,"current":false,"isExpanded":false,"link":"","children":["map-in-cpp","containers-in-cpp","set-in-cpp","multiset-in-cpp","multimap-in-cpp","stack-in-cpp","queue-in-cpp","deque-in-cpp","vector-in-cpp","list-in-cpp","priority-queue-cpp","pair-in-cpp"],"parent":"-1","prev":"","next":"","image":null},"map-in-cpp":{"slug":"map-in-cpp","title":"Map in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/map-in-cpp/","children":[],"parent":"module_stl","prev":"file-handling-in-cpp","next":"containers-in-cpp","image":null},"containers-in-cpp":{"slug":"containers-in-cpp","title":"C++ Container Types and Sequences","read":false,"current":false,"isExpanded":false,"link":"/cpp/containers-in-cpp/","children":[],"parent":"module_stl","prev":"map-in-cpp","next":"set-in-cpp","image":null},"set-in-cpp":{"slug":"set-in-cpp","title":"Set in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/set-in-cpp/","children":[],"parent":"module_stl","prev":"containers-in-cpp","next":"multiset-in-cpp","image":null},"multiset-in-cpp":{"slug":"multiset-in-cpp","title":"Multiset in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/multiset-in-cpp/","children":[],"parent":"module_stl","prev":"set-in-cpp","next":"multimap-in-cpp","image":null},"multimap-in-cpp":{"slug":"multimap-in-cpp","title":"Multimap in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/multimap-in-cpp/","children":[],"parent":"module_stl","prev":"multiset-in-cpp","next":"stack-in-cpp","image":null},"stack-in-cpp":{"slug":"stack-in-cpp","title":"Stack in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/stack-in-cpp/","children":[],"parent":"module_stl","prev":"multimap-in-cpp","next":"queue-in-cpp","image":null},"queue-in-cpp":{"slug":"queue-in-cpp","title":"Queue in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/queue-in-cpp/","children":[],"parent":"module_stl","prev":"stack-in-cpp","next":"deque-in-cpp","image":null},"deque-in-cpp":{"slug":"deque-in-cpp","title":"Deque in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/deque-in-cpp/","children":[],"parent":"module_stl","prev":"queue-in-cpp","next":"vector-in-cpp","image":null},"vector-in-cpp":{"slug":"vector-in-cpp","title":"Vector in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/vector-in-cpp/","children":[],"parent":"module_stl","prev":"deque-in-cpp","next":"list-in-cpp","image":null},"list-in-cpp":{"slug":"list-in-cpp","title":"List in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/list-in-cpp/","children":[],"parent":"module_stl","prev":"vector-in-cpp","next":"priority-queue-cpp","image":null},"priority-queue-cpp":{"slug":"priority-queue-cpp","title":"Priority Queue in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/priority-queue-cpp/","children":[],"parent":"module_stl","prev":"list-in-cpp","next":"pair-in-cpp","image":null},"pair-in-cpp":{"slug":"pair-in-cpp","title":"Pair in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/pair-in-cpp/","children":[],"parent":"module_stl","prev":"priority-queue-cpp","next":"lambda-function-cpp","image":null},"module_miscellaneous":{"slug":"module_miscellaneous","title":"Miscellaneous","read":false,"current":false,"isExpanded":false,"link":"","children":["lambda-function-cpp","lvalue-and-rvalue","concurrent-programming","new-operator-in-cpp","uses-of-cpp"],"parent":"-1","prev":"","next":"","image":null},"lambda-function-cpp":{"slug":"lambda-function-cpp","title":"Lambda Expression in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/lambda-function-cpp/","children":[],"parent":"module_miscellaneous","prev":"pair-in-cpp","next":"lvalue-and-rvalue","image":null},"lvalue-and-rvalue":{"slug":"lvalue-and-rvalue","title":"lvalue and rvalue in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/lvalue-and-rvalue/","children":[],"parent":"module_miscellaneous","prev":"lambda-function-cpp","next":"concurrent-programming","image":null},"concurrent-programming":{"slug":"concurrent-programming","title":"Concurrent Programming and Low-Level Programming","read":false,"current":false,"isExpanded":false,"link":"/cpp/concurrent-programming/","children":[],"parent":"module_miscellaneous","prev":"lvalue-and-rvalue","next":"new-operator-in-cpp","image":null},"new-operator-in-cpp":{"slug":"new-operator-in-cpp","title":"new Operator in C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/new-operator-in-cpp/","children":[],"parent":"module_miscellaneous","prev":"concurrent-programming","next":"uses-of-cpp","image":null},"uses-of-cpp":{"slug":"uses-of-cpp","title":"Uses of C++","read":false,"current":false,"isExpanded":false,"link":"/cpp/uses-of-cpp/","children":[],"parent":"module_miscellaneous","prev":"new-operator-in-cpp","next":"","image":null}},"nextSlug":"dynamic-member","prevSlug":"friend-function-in-cpp","breadcrumb":[{"slug":"/hubs","title":"Reading Tracks","link":"/hubs","type":"reading-track"},{"slug":"cpp","title":"C++ Tutorial","link":"/cpp"},{"slug":"dynamic-memory-allocation-in-cpp","title":"Dynamic Memory Allocation in C++","link":""}],"hubInfo":{"slug":"cpp","title":"C++ Tutorial","eligible_for_certificate":false},"mappedCourseSlug":"cpp-beginners"}},"objectType":"Article","metaDetails":{"title":"Dynamic Memory Allocation in C++ - Scaler Topics","description":"In this article by Scaler Topics, we will see an explanation of memory management and types of memory (stack and heap) in C++ Language, read to know more.","category":"C++","author":"Abhishek Chandra","publish_date":"undefined"},"contentData":"\n\n:::section{.abstract}\n\n## Overview\n\nThe process of allocating or de-allocating a block of memory during the execution of a program is called **Dynamic Memory Allocation**. The operators **new** and **delete** are utilized for dynamic memory allocation in C++ language, **new** operator is used to allocate a memory block, and **delete** operator is used to de-allocate a memory block which is allocated by using new operator.\n\n:::\n\n:::section{.main}\n\n## C++ Program Memory Management \n\nWhen we run a C++ program on our machine, it requires some space to store its instructions (statements), local variables, global variables, and various other [functions in C++](https://www.scaler.com/topics/cpp/functions-in-cpp/). This space required to run a C++ Program is known as **memory** in computers.\n\nThere are **two types of memory** in our system, **Static Memory and Dynamic Memory**.\n\n* **Static Memory:** It is a **constant space** allocated by the operating system during the **compile time** of a C++ program and it internally uses **stack** data structure to manage the static memory allocation. We can't reallocate the space consumed by the program until its execution is over.\n\n* **Dynamic Memory:** It is the memory that can be allocated or de-allocated by the operating system during the **run-time** of a C++ program. It is more efficient than static memory because we can **de-allocate and reuse** our memory during the run-time of our program.\n\nThe memory used by a C++ program can be divided further into four parts:\n\n1. Run-time Stack (Static Memory)\n2. Static Data Memory (for Global and Static Variables) \n3. Instructions / Statements (Static Memory)\n4. Heap (Dynamic Memory)\n\n![Types of Memory](https://scaler.com/topics/images/types-of-memory.webp)\n\n### The Stack memory\n\n* Our operating system **allocates a constant space** during compile-time of a C++ program, this space is known as **Stack memory**. \n* Stack memory is used to **hold functions**, different variables, and local statements that exist in the function definition. \n* Stack is a part of the static memory in our system and it constitutes the majority of our system's static memory.\n\n### The Heap Memory\n\n* **Heap memory** is also known as the **dynamic memory** in our system. It can be thought of as a large block of memory that is **expandable and shrinkable** during the execution of a program.\n* **Allocation and De-allocation of memory blocks** during the execution of a program can be done using **new** and **delete** operators in C++ (these operators are discussed later in the article).\n* Heap memory can be expanded as long as we do not exhaust the machine memory itself. It is not good from a programming perspective to completely use the machine memory to avoid errors, thus we must use the heap memory carefully.\n\n\n:::\n\n:::section{.main}\n\n## Types of Memory Allocation\n\n\n### 1. Static Memory Allocation in C++ (Compile-time Memory Allocation)\n\n* When memory is allocated at compile-time, it is referred to as **Static Memory Allocation**.\n* A fixed space is allocated for the local variables, function calls, and local statements, that **can not** be changed during the execution of the program.\n* We **can not allocate or de-allocate a memory block** once the execution of the program starts.\n* We **can't re-use** the static memory while the program is running. As a result, it is less effective.\n\n### 2. Dynamic Memory Allocation in C++ (Run-time Memory Allocation)\n\n* When memory is allocated or de-allocated during run-time, it is referred to as **Dynamic Memory Allocation** in C++.\n* A variable space is allocated that **can** be changed during the execution of the program.\n* We use dynamic/heap memory to allocate and de-allocate a block of memory during the execution of the program using **new** and **delete** operators.\n* We **can** re-use our heap memory during the run-time of our program. As a result, it is highly effective.\n\n\u003c!-- What is the main advantage of dynamic memory allocation over static memory allocation in C++?\n\nOptions:\nA) Dynamic memory allows memory size to be adjusted during runtime.\nB) Dynamic memory uses less overall memory.\nC) Dynamic memory allocation is faster.\nD) Dynamic memory can be allocated on the stack.\n\nCorrect Answer: A) Dynamic memory allows memory size to be adjusted during runtime. --\u003e\n\n:::\n\n:::section{.quiz_pop}\n:::\n\n:::section{.main}\n\n## Why Dynamic Memory Allocation?\n\nThere were some drawbacks of **stack memory or static memory allocation**, like the space allocated for the stack **can not be expanded** during the execution of a C++ program or we can't keep variables in the program till the time we want. So, to overcome these drawbacks, we use the **Dynamic Memory Allocation concepts**. \n\nDynamic Memory Allocation is also a very essential topic in the field of **data structures**, and it is utilized practically in all data structures. For example, dynamic arrays, linked lists, queues, trees, stack, etc. uses DMA to allocate and de-allocate memory blocks during the execution of a C++ program. \n\n:::\n\n\n:::section{.main}\n\n## How is it Different from Memory Allocated to Normal Variables?\n\nThe operating system uses static memory allocation for normal data-type variables and arrays, for example, **`int r;`**, **`double arr[10];`**, **`char name[20];`**, etc., the memory is automatically allocated at compile time and de-allocated when the function, block, or program finishes by the operating system. \n\nThe operating system uses dynamic memory allocation in C++ for dynamically allocated variables, for example, **`int* ptr = new int;`**, **`int* arr = new int[6];`**. Dynamically allocated memory does not get de-allocated until the program terminates. So, a programmer must de-allocate the memory, when it is no longer required. Memory leaks can occur when a programmer fails to de-allocate a dynamically allocated memory.\n\n:::\n\n\n:::section{.main}\n\n## How is Memory Allocated/De-Allocated in C++?\n\nIn C Language, before allocating or de-allocating memory dynamically (at run-time), we have to include **`\u003cstdlib.h\u003e`** header file to use the library functions like **`malloc()`**, **`calloc()`**, **`realloc()`** and **`free()`**.\n\nIn C++ Language, **new** and **delete** operators are pre-defined in the C++ Standard Library and don't require to include any library file for run-time allocation and de-allocation of memory blocks. Although we can use **`malloc()`**, **`calloc()`**, and other functions in C++ as well by adding the **`\u003cstdlib.h\u003e`** header file because of the backward compatibility of C++ with C Language. This article explains the **new** and **delete** operators of the C++ language. Visit [Dynamic Memory Allocation in C - Scaler Topics](https://www.scaler.com/topics/c/dynamic-memory-allocation-in-c/) to know more about DMA functions in C Language.\n\n:::\n\n:::section{.main}\n\n## Dynamic Memory Allocation \u0026 De-allocation Criteria\n\n### 1. Creating the Dynamic Space in Memory.\n\nDuring the dynamic memory allocation in C++, first, we have to create a dynamic space (in the heap memory). We use the **new** operator to create a dynamic space. \n\n### 2. Storing its Address in a Pointer\n\nOnce a **dynamic space** a created, we have to store the address of the **allocated space in a pointer variable** to access and modify the contents of the **memory block**.\n\n### 3. Deleting the Allocated Space\n\nOnce the user does not require the memory block, we delete the allocated space using the **delete** operator to free up the heap memory.\n\n:::\n\n\n:::section{.main}\n\n## The \"new\" operator in C++\n\nThe **new** operator in C++ is used to **dynamically allocate a block of memory and store its address** in a pointer variable during the execution of a C++ program if enough memory is available in the system.\n\n### Syntax for \"new\" operator:\n\n```cpp\ndata_type* ptr_var = new data_type;\n```\n\n* **`ptr_var`** is a pointer, which stores the address of the type **`data_type`**. \n* Any pre-defined data types, like **`int`**, **`char`**, etc., or other user-defined data types, like classes, can be used as the **`data_type`** with the **new** operator.\n\n### Example C++ Program:\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=2f1c6a4514666588e44f\n// how to allocate memory using the new operator example\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() \n{\n // dynamically allocating an integer memory block\n int* ptr = new int;\n\n // storing a value at the memory pointed by ptr\n *ptr = 12;\n\n cout \u003c\u003c \"Value at memory pointed by ptr= \" \u003c\u003c *ptr;\n\n return 0;\n}\n```\n\n**Output:**\n\n```plaintext\nValue at memory pointed by ptr= 12\n```\n\n**Explanation:** \n\n* A memory block is allocated using the **new** operator and the address of the memory block has been stored in the **`ptr`** pointer. \n* (**`*ptr`**) represents the value at the allocated memory location. We have assigned **`12`** in the memory using **`*ptr = 12`** expression.\n\n### Initializing Dynamic Memory\n\n**Syntax:**\n\n```cpp\ndata_type* ptr_var = new data-type(value);\n```\n\n\n**Example C++ program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=8c718e57ddbf66344dc3\n#include \u003ciostream\u003e\nusing namespace std;\n\nint main() \n{\n // dynamically allocating an integer memory block\n // with 12 as its initial value\n int* ptr = new int(12);\n\n cout \u003c\u003c \"Value at memory pointed by ptr= \" \u003c\u003c *ptr;\n\n return 0;\n}\n```\n\n**Output:**\n\n```plaintext\nValue at memory pointed by ptr= 12\n```\n\n### What Happens if the System's Memory Runs out During the Execution of the Program?\n\nWhen there is insufficient memory in the heap segment during the run-time of a C++ program, the new request for allocation fails by throwing an exception of type **`std::bad alloc`**. It can be avoided using a **nothrow** argument with the **new** operator. When we use **nothrow** with **new**, it returns a **NULL** pointer. So, the pointer variable should be checked that is formed by **new** before utilizing it in a program.\n\n**Example:**\n\n```cpp\nint* ptr = new(nothrow) int;\n\nif (ptr == NULL)\n{\n cout \u003c\u003c \"Allocation Failed!\\n\";\n}\n```\n\n:::\n\n\n:::section{.main}\n\n## The \"delete\" Operator in C++\n\nThe **delete** operator is used to de-allocate the block of memory, which is dynamically allocated using the **new** operator. Since, a programmer must de-allocate a block of memory, once it is not required in the program. So, we have to use the **delete** operator to avoid memory leaks and program crash errors, which occur due to the exhaustion of the system's memory. \n\n### Syntax:\n\nSyntax to delete a single block of memory:\n\n```cpp\ndelete ptr_var;\n```\n\nSyntax to delete an array of memory:\n\n```cpp\ndelete [] ptr_var;\n```\n\n\n### Example C++ Program:\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=c1eef4ca83c94a024b75\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nint main() \n{\n // allocating a new int stars variable using new\n int* stars = new int;\n *stars = 5000;\n\n cout\u003c\u003c\"Visible stars in the sky: \"\u003c\u003c*stars;\n\n // stars memory deallocated using the delete operator\n delete stars;\n\n cout\u003c\u003c\"\\nGarbage value: \"\u003c\u003c*stars;\n\n stars = NULL;\n\n return 0;\n}\n```\n\n\n**Output:**\n\n```plaintext\nVisible stars in the sky: 5000\nGarbage value: 1491762488\n```\n\n(output garbage value is compiler dependent and will be different at each run)\n\n\n**Explanation:**\n\n* A memory block for the **stars** pointer is allocated using the **new** operator and the address of the memory block has been stored in the **stars** pointer. \n* We have used the **delete** operator to de-allocate the memory pointed by the **stars** pointer, as it is no longer required in our program.\n* The memory is de-allocated but the **stars** pointer is still pointing to some garbage location in the memory. So, it will show **garbage value** if printed on the output screen. We have assigned **NULL** to the **stars** pointer in the end to avoid the situation of a [dangling pointer](https://www.scaler.com/topics/c/dangling-pointer-in-c/).\n\n**Image Explanation:**\n![Dynamic Memory Allocation in C++](https://scaler.com/topics/images/dynamic-memory-allocation-in-cpp.webp)\n\n \n\u003c!-- Which statement is true about the new operator in C++?\n\nOptions:\nA) It can only allocate memory for integers.\nB) It automatically deallocates memory when it's no longer needed.\nC) It initializes the memory block to zero.\nD) It can throw an exception if memory allocation fails.\n\nCorrect Answer: D) It can throw an exception if memory allocation fails --\u003e\n:::\n\n:::section{.quiz_pop}\n:::\n\n:::section{.main}\n\n## Dynamic Memory Allocation in C++ for Arrays\n\n### Allocating a Block of Memory Using the \"new\" Operator\n\nThe **new** operator can also be used to allocate a block of memory (an array) of any **`data_type`**.\n\n**Syntax:**\n\n```cpp\ndata_type* ptr_var = new data_type[size_of_the_array];\n```\n\n**Example**\n\n```cpp\nchar* name = new char[10];\n```\n\n\n\n### Standard Array Declaration vs Using the \"new\" Operator\n\nThe most significant distinction between **standard arrays and a dynamically allocated array** is that standard arrays are de-allocated by the [**online C++ compiler**](https://www.scaler.com/topics/cpp/online-cpp-compiler/) when the function execution finishes or it goes out of scope. While with dynamically allocated arrays, arrays always remain in the memory until either the programmer **de-allocates** them or the program execution finishes.\n\n**Syntax for normal array declaration:**\n\n```cpp\nint arr[5];\n```\n\n**Syntax for dynamically allocated array:**\n\n```cpp\nint* arr = new int[5];\n```\n\n\n\n**Example C++ Program with `new` operator:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=5706cdd454d80da2aa17\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nint main() \n{\n\t// dynamically allocating an integer array of size 5 using new operator \n\tint* arr = new int[5];\n\n\tcout \u003c\u003c \"Enter 5 values in the array: \";\n\n\t// taking 5 values as an input from the user\n\tfor(int i = 0; i \u003c 5; i++)\n\t{\n\t\tcin \u003e\u003e arr[i];\n\t}\t\n\n\t// displaying the array elements in the output\n\tcout \u003c\u003c \"\\nArray elements: \";\n\tfor(int i = 0; i \u003c 5; i++)\n\t{\n\t\tcout \u003c\u003c arr[i] \u003c\u003c \" \";\n\t}\n\n\t// dynamically deallocating the array using delete operator\n\tdelete [] arr;\n\n\t// garbage values will be displayed as \n\t// the pointer will point to some deallocated locations\n\tcout \u003c\u003c \"\\nGarbage array values after deallocation of array memory: \";\n\tfor(int i = 0; i \u003c 5; i++)\n\t{\n\t\tcout \u003c\u003c arr[i] \u003c\u003c \" \";\n\t}\n\n\treturn 0;\n}\n```\n\n**Custom Input:**\n```cpp\nEnter 5 values in the array: 1 2 3 4 5\n```\n\n**Output:**\n\n```plaintext\nArray elements: 1 2 3 4 5 \nGarbage array values after deallocation of array memory: -1544938184 32704 -1544938184 32704 5 \n```\n\n(output garbage values are compiler dependent and different at each run)\n\n**Explanation:** \n\n- We have created a dynamically allocated array using the **new** operator. \n- Then, we have taken input for the array elements from the user and printed the array elements.\n- With the use of the **delete** operator on the array pointer **`arr`**, we have de-allocated the array memory. Now, the array location will contain **garbage values** as seen in the output.\n\n:::\n\n:::section{.main}\n\n## Dynamic Memory Allocation in C++ for Objects\n\nWe can dynamically allocate memory for objects also. When we create an object of a class, a constructor function is invoked. Constructor is a member function of a class that is used to initialize the object. Also, when the object goes out of scope or gets **de-allocated**, a **destructor** function is invoked. Destructor is also a **class member function** that helps in knowing when the object's memory gets **deleted**.\n\nWe use pointers once more for allocating memory to objects.\n\n**Example C++ Program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=996952e543cc14e13181\n#include \u003ciostream\u003e\nusing namespace std;\n\nclass Animal \n{\n public:\n Animal() { \n cout \u003c\u003c \"Animal class constructor invoked!\" \u003c\u003cendl; \n }\n ~Animal() { \n cout \u003c\u003c \"Animal class destructor invoked!\" \u003c\u003cendl; \n }\n};\n\nint main() \n{\n // memory allocated for dog object of type Animal\n // constructor will be invoked\n Animal* dog = new Animal; \n\n // memory deallocated for dog object of type Animal\n // destructor will be invoked\n delete dog; \n\n return 0;\n}\n```\n\n**Output:**\n\n```plaintext\nAnimal class constructor invoked!\nAnimal class destructor invoked!\n```\n\n**Explanation:** We have created a class **Animal** with [constructor and destructor](https://www.scaler.com/topics/cpp/constructor-and-destructor-in-cpp/) member functions. In the **`main()`** function, we have created a **dog** object of class **Animal** using the **new** operator, which invokes the constructor function of the **Animal** class. When we have used the **delete** operator to de-allocate the **dog** object memory, the destructor function is invoked.\n\n:::\n\n:::section{.main}\n\n## Comparison with \"malloc()\", \"calloc()\", and \"free()\" Functions of C.\n\nFirst, let's see the small definitions of **`malloc()`**, **`calloc()`**, and **`free()`** library function to get a basic understanding of the functions.\n\n| C Functions | Definition| Syntax |\n| :------------: | :-------: | :-----------: |\n| [malloc()](#malloc-examples) | It is used to allocate memory of the argument's size (in bytes) and returns a void pointer to the allocated pointer's first byte.| **`(cast-data-type *)malloc(size-in-bytes)`** |\n| [calloc()](#calloc-examples) | It is used to allocate space as an array of elements, it also initializes all the elements with `0` and returns a void pointer.| **`(cast-data-type *)calloc(num, size-in-bytes)`** |\n| [free()](#free-example) | It is used to clear the allocated space (de-allocate) from the heap memory.| **`free(ptr)`** |\n:::\n:::section{.tip}\n\n**Note:** The **`malloc()`** and the **`calloc()`** function returns a void pointer, so we have to typecast them into the required data types before using the allocated memory.\n:::\n:::section{.main}\n### \"new\" vs \"malloc()\" and \"calloc()\"\n\nThe **new** operator has a similar working as [malloc() and calloc()](https://www.scaler.com/topics/difference-between-malloc-and-calloc-in-c/) functions because these all are used to allocate memory during the execution of a C/C++ program but, when the **new** operator is used with objects it invokes the constructor function of the class, while **`malloc()`** and **`calloc()`** doesn't invoke the constructor function.\n\n**Example C++ Program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=963d80336dc2f07ad348\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nclass Animal \n{\n public:\n Animal() { \n cout \u003c\u003c \"Animal class constructor invoked!\" \u003c\u003cendl; \n }\n ~Animal() { \n cout \u003c\u003c \"Animal class destructor invoked!\" \u003c\u003cendl; \n }\n};\n\nint main() \n{\n\t// memory allocated for dog object of type Animal using the new operator\n\t// here, the constructor will be called 1 time.\n\tAnimal* dog = new(nothrow) Animal; \n\n\t// 5 blocks of memory allocated for object dogs using new\n\t// here, the constructor will be called 5 times.\n\tAnimal* dogs = new(nothrow) Animal[5];\n\n\t// memory allocated for cat object of type Animal using the malloc function,\n\t// constructor will not be called.\n\tAnimal* cat = (Animal*)malloc(sizeof(Animal));\n\n\t// 5 blocks of memory allocated for object dogs using calloc function,\n\t// constructor will not be called.\n\tAnimal* cats = (Animal*)calloc(5, sizeof(Animal));\n\n\treturn 0;\n}\n```\n\n**Output:**\n\n```plaintext\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\nAnimal class constructor invoked!\n```\n\n**Explanation:** We can see that, when an object **dog** was created using the **new** operator, the constructor is invoked. Also, when we have created an array of **Animal** class (**`dogs`**) with **`5`** elements, the default constructor is invoked **`5`** times (constructor is invoked **`6`** times in total). Whereas, when an object was created using the **`malloc()`** or **`calloc()`** function, the constructor function is not called.\n\n\n### \"delete\" vs \"free()\"\n\nThe **delete** operator is also similar to the **`free()`** function because both methods are used to de-allocate memory during the execution of a C/C++ program but, when the **delete** operator is used with objects it invokes the destructor function of the class when the object is de-allocated, while **`free()`** doesn't invoke the destructor function.\n\n**Example C++ Program:**\n\n```cpp::https://www.scaler.com/topics/cpp/online-cpp-compiler/?content_slug=12d6b30f4568be996ca9\n#include \u003ciostream\u003e\n\nusing namespace std;\n\nclass Animal \n{\n public:\n Animal() { \n cout \u003c\u003c \"Animal class constructor invoked!\" \u003c\u003cendl; \n }\n ~Animal() { \n cout \u003c\u003c \"Animal class destructor invoked!\" \u003c\u003cendl; \n }\n};\n\nint main() \n{\n\t// memory allocated for dog object of type Animal using the new operator\n\t// here, the constructor will be called 1 time.\n\tAnimal* dog = new(nothrow) Animal; \n\n\t// memory allocated for cat object of type Animal using the malloc function,\n\t// constructor will not be called.\n\tAnimal* cat = (Animal*)malloc(sizeof(Animal));\n\n\t// deallocates the memory for dog object using delete operator,\n\t// destructor will be called.\n\tdelete dog;\n\n\t// deallocates the memory for cat object using free funtion but,\n\t// destructor will not be called\n\tfree(cat);\n\n\treturn 0;\n}\n```\n\n**Output:**\n\n```plaintext\nAnimal class constructor invoked!\nAnimal class destructor invoked!\n```\n\n**Explanation:** We can see that, when an object **dog** was created using the **new** operator, the constructor is invoked. Also, we have created an object of **Animal** class (**`cat`**) using the **`malloc()`** function. When the **delete** operator is used with the **dog** object, it invokes the default destructor function. Whereas, when the **`free()`** function is called with the **cat** object, the destructor function is not called.\n\n\u003c!-- Why should the delete operator be used instead of free() in C++ when dealing with objects?\n\nOptions:\nA) delete automatically calls the destructor, whereas free() does not.\nB) free() can allocate memory, but delete cannot.\nC) delete uses less memory than free().\nD) free() is faster than delete.\n\nCorrect Answer: A) delete automatically calls the destructor, whereas free() does not. --\u003e\n\n:::\n\n:::section{.quiz_pop}\n::: \n\n:::section{.summary}\n\n## Conclusion\n- A system's memory is one of the most important resources available to us since it can be used as both static memory and dynamic memory. \n- Allocation and de-allocation of memory blocks during run-time is known as **Dynamic Memory Allocation** in C++.\n- DMA is a very essential concept in the field of data structures as Linked Lists, Stacks, Queues, Trees, etc., requirements allocation and de-allocation of memory blocks at run-time.\n- The **new** operator is used to allocate a memory block, while the **delete** operator is used to de-allocate a memory block.\n- In C language, we use **`malloc()`**, **`calloc()`**, and **free** functions, while in C++ language we use **new** and **delete** operators to allocate and de-allocate memory blocks at run-time. \n\n\n \n:::\n:::section{.main}\n## Read More:\n- [Inheritance in C++](https://www.scaler.com/topics/cpp/inheritance-in-cpp/).\n- [Learn about Data Types in C++](https://www.scaler.com/topics/cpp/data-types-in-cpp/).","mediaList":["https://scaler.com/topics/images/types-of-memory.webp","https://scaler.com/topics/images/dynamic-memory-allocation-in-cpp.webp"],"pageClass":"articlePage","rootClass":"articleLayout","subProduct":"article","fallback":{"https://www.scaler.com/topics/api/v1/search/courses/1/6/":[{"slug":"python-for-beginners","title":"Python Course for Beginners With Certification: Mastering the Essentials","category_type":"topics_course","cover_image_thumbnail":"https://www.scaler.com/topics/images/course_card_image_pybeg.webp","featured_image":"https://www.scaler.com/topics/images/course_featured_image_pybeg.webp","modules_count":16,"description":"Welcome to the free Python course with certificate for beginners, designed to help you kickstart your programming journey. This comprehensive Python course online offers a certificate upon completion, covering essential topics like basic Python fundamentals, data structures, object-oriented programming, and more. With 9 hours and 48 minutes of content, you'll gain the knowledge and confidence to start working on your Python projects.","eligible_for_certificate":true,"instructor_name":"Rahul Janghu","instructor_image":"https://www.scaler.com/topics/images/rahul_janghu.webp","company_image":"https://www.scaler.com/topics/images/Scaler.webp","star_headline":"4.90","headline":"Software Engineer and Instructor at Scaler","app_exclusive":false,"user_registration_count":175844,"is_popular":true,"first_entity":{"type":"Video","uuid":660},"category_meta_url":null,"total_time":"9h 44m","total_entities_count":131,"bookmarked":null,"programs":["data_science","programming_languages"]},{"slug":"java-beginners","title":"Java Course - Mastering the Fundamentals","category_type":"topics_course","cover_image_thumbnail":"https://www.scaler.com/topics/images/Java-master-image.webp","featured_image":"https://www.scaler.com/topics/images/java-master.webp","modules_count":12,"description":"Embark on your programming journey with our Free Java Course with Certificate. Master the fundamentals of Java and gain the skills needed for advanced Java development. This easy-to-follow course is designed with beginners in mind, offering a structured learning path to specialize in Java programming. With no prerequisites, this online Java course empowers you to learn Java at your own pace and take the first step toward a promising career in tech.","eligible_for_certificate":true,"instructor_name":"Tarun Luthra","instructor_image":"https://www.scaler.com/topics/images/instructor-tarun.webp","company_image":"https://www.scaler.com/topics/images/Scaler.webp","star_headline":"5 Star Instructor on Scaler","headline":"Software Engineer \u0026 Instructor","app_exclusive":false,"user_registration_count":143336,"is_popular":true,"first_entity":{"type":"Video","uuid":1},"category_meta_url":null,"total_time":"8h 9m","total_entities_count":95,"bookmarked":null,"programs":["academy","programming_languages"]},{"slug":"javascript-beginners","title":"JavaScript Course With Certification: Unlocking the Power of JavaScript","category_type":"topics_course","cover_image_thumbnail":"https://www.scaler.com/topics/images/Course_Listing_312x136_MrinalBhattacharya","featured_image":"https://www.scaler.com/topics/images/Course_FI_816x352_MrinalBhattacharya.webp","modules_count":9,"description":"Kickstart your journey into web development with this free JavaScript course online with a certificate. Designed for beginners, this comprehensive JavaScript online course covers the essential concepts and skills needed to master Javascript, one of the most popular and widely used programming languages in the world. With a course duration of 10 hours and 9 minutes, you'll learn everything from the basics to advanced techniques, all at your own pace.","eligible_for_certificate":true,"instructor_name":"Mrinal Bhattacharya","instructor_image":"https://www.scaler.com/topics/images/mrinal_bhattacharya.webp","company_image":"https://www.scaler.com/topics/images/Scaler.webp","star_headline":"4.8","headline":null,"app_exclusive":false,"user_registration_count":78003,"is_popular":true,"first_entity":{"type":"Video","uuid":1637},"category_meta_url":null,"total_time":"10h 14m","total_entities_count":78,"bookmarked":null,"programs":["academy","programming_languages","frontend_development"]},{"slug":"dbms","title":"DBMS Course - Master the Fundamentals and Advanced Concepts","category_type":"topics_course","cover_image_thumbnail":"https://www.scaler.com/topics/images/course_card_image_dbms.webp","featured_image":"https://www.scaler.com/topics/images/course_featured_image_dbms.webp","modules_count":16,"description":"Scaler Topics free DBMS course is designed to help beginners learn about the fundamental concepts of database management systems. The course is completely online, and it comes with a free certificate of completion that you can add to your resume or LinkedIn profile. You'll learn about the most popular DBMS like MySQL, Oracle, and SQL Server, as well as the theoretical foundations of databases.","eligible_for_certificate":true,"instructor_name":"Srikanth Varma","instructor_image":"https://www.scaler.com/topics/images/srikant-varma_instructor.webp","company_image":"https://www.scaler.com/topics/images/Scaler.webp","star_headline":"5","headline":"Lead DSML Instructor at Scaler","app_exclusive":false,"user_registration_count":74784,"is_popular":false,"first_entity":{"type":"Video","uuid":1620},"category_meta_url":null,"total_time":"1d 5h 17m","total_entities_count":90,"bookmarked":null,"programs":["academy"]},{"slug":"cpp-beginners","title":"C++ Course: Learn the Essentials","category_type":"topics_course","cover_image_thumbnail":"https://www.scaler.com/topics/images/cpp_card_master.webp","featured_image":"https://www.scaler.com/topics/images/cpp-master.webp","modules_count":14,"description":"Gain programming expertise with our C++ Course! Covering basics to advanced concepts, this online program provides a comprehensive curriculum encompassing environment setup, variables, conditional statements, loops, functions, pointers, arrays, sorting, character arrays, strings, and more. This C++ online course is perfect for beginners or seasoned programmers looking to enhance their skills and earn a certificate.","eligible_for_certificate":true,"instructor_name":"Prateek Narang","instructor_image":"https://www.scaler.com/topics/images/instructor-prateek.webp","company_image":"https://www.scaler.com/topics/images/Scaler.webp","star_headline":"5 Star Instructor on Udemy","headline":"Instructor \u0026 Engineering Lead","app_exclusive":false,"user_registration_count":66813,"is_popular":false,"first_entity":{"type":"Video","uuid":89},"category_meta_url":null,"total_time":"9h 24m","total_entities_count":105,"bookmarked":null,"programs":["academy","programming_languages"]},{"slug":"python-sql-data-science","title":"Python and SQL for Data Science","category_type":"topics_course","cover_image_thumbnail":"https://www.scaler.com/topics/images/course_card_image_pds.webp","featured_image":"https://www.scaler.com/topics/images/course_featured_image_pds.webp","modules_count":8,"description":"Introducing the Free Data Science with Python and SQL Certification Course Online, a comprehensive beginner's program designed to help aspiring data scientists learn the essential skills in the rapidly growing field of data science. This course offers a unique blend of practical and theoretical knowledge, combining the powerful programming language Python and the versatile database management system SQL to help you analyze, visualize, and interpret data efficiently.\n","eligible_for_certificate":true,"instructor_name":"Srikanth Varma","instructor_image":"https://www.scaler.com/topics/images/srikant-varma_instructor.webp","company_image":"https://www.scaler.com/topics/images/Scaler.webp","star_headline":"5","headline":"Lead DSML Instructor at Scaler","app_exclusive":false,"user_registration_count":61626,"is_popular":false,"first_entity":{"type":"Video","uuid":1624},"category_meta_url":null,"total_time":"14h 46m","total_entities_count":73,"bookmarked":null,"programs":["data_science"]}],"/course/cpp-beginners":[{"slug":"cpp-beginners","title":"C++ Course: Learn the Essentials","cover_image_thumbnail":"https://www.scaler.com/topics/images/cpp_card_master.webp","modules_count":14,"eligible_for_certificate":true,"instructors_data":[{"id":1,"name":"Prateek Narang","email":"prateek.narang@scaler.com","headline":"Instructor \u0026 Engineering Lead","courses":"C++, Data Structures, Algorithms","total_scaler_students":"1600+","lectures_delivered":"325","star_headline":"5 Star Instructor on Udemy","total_courses":1,"bio":"Prateek Narang, popular as Prateek Bhaiya is renowned programming instructor and former Google engineer. He has done his B.Tech from Delhi Technological University, and has taught over 100k students in online and offline modes. He is also co-founder of Coding Minutes and his courses are also popular on Udemy. He also leads initiatives at Scaler Topics bringing high quality free content and takes live sessions at Scaler Academy.","company_image":"https://www.scaler.com/topics/images/Scaler.webp","cover_image":"https://www.scaler.com/topics/images/instructor-prateek.webp","app_cover_image":null}],"app_exclusive":false,"user_registration_count":0}],"https://www.scaler.com/topics/api/v1/recommendations/Article/dynamic-memory-allocation-in-cpp/6/cpp":[{"id":"276","type":"basic_article","attributes":{"title":"Dynamic Memory Allocation in C","slug":"dynamic-memory-allocation-in-c","published_at":"2021-12-17T00:00:00.000Z","last_updated_at":"2024-04-20T07:32:39.000Z","read_time":null}},{"id":"806","type":"basic_article","attributes":{"title":"Pointers in C++","slug":"pointers-in-cpp","published_at":"2022-03-24T00:00:00.000Z","last_updated_at":"2024-02-20T07:09:40.000Z","read_time":null}},{"id":"3030","type":"basic_article","attributes":{"title":"C++ free() Function","slug":"cpp-free-function","published_at":"2022-11-14T00:00:00.000Z","last_updated_at":"2022-12-10T00:00:00.000Z","read_time":null}},{"id":"3096","type":"basic_article","attributes":{"title":"C++ Accumulate","slug":"cpp-accumulate","published_at":"2022-11-17T00:00:00.000Z","last_updated_at":"2023-05-04T00:00:00.000Z","read_time":null}},{"id":"3818","type":"basic_article","attributes":{"title":"What is the Difference Between Static and Dynamic Memory Allocation?","slug":"memory-allocation-in-cpp","published_at":"2022-12-20T00:00:00.000Z","last_updated_at":"2023-05-04T13:29:34.000Z","read_time":null}},{"id":"4896","type":"basic_article","attributes":{"title":"What is Dynamic Constructor in C++?","slug":"dynamic-constructor-in-cpp","published_at":"2023-03-13T00:00:00.000Z","last_updated_at":"2023-10-09T00:00:00.000Z","read_time":null}}]}},"__N_SSG":true},"page":"/[...slug]","query":{"slug":["cpp","dynamic-memory-allocation-in-cpp"]},"buildId":"6jK709HyxmpV6buc4IRmo","assetPrefix":"https://d1g0iq4cbcvjcd.cloudfront.net/topics","runtimeConfig":{"assetPrefix":"https://d1g0iq4cbcvjcd.cloudfront.net/topics","basePath":"/topics"},"isFallback":false,"dynamicIds":[65177,33161,43766,41631,96770,69605],"gsp":true,"scriptLoader":[]}</script></body></html>

Pages: 1 2 3 4 5 6 7 8 9 10