Search

6.9 — Dynamic memory allocation with new and delete

The need for dynamic memory allocation

C++ supports three basic types of memory allocation, of which you’ve already seen two.

  • Static memory allocation happens for static and global variables. Memory for these types of variables is allocated once when your program is run and persists throughout the life of your program.
  • Automatic memory allocation happens for function parameters and local variables. Memory for these types of variables is allocated when the relevant block is entered, and freed when the block is exited, as many times as necessary.
  • Dynamic memory allocation is the topic of this article.

Both static and automatic allocation have two things in common:

  • The size of the variable / array must be known at compile time.
  • Memory allocation and deallocation happens automatically (when the variable is instantiated / destroyed).

Most of the time, this is just fine. However, you will come across situations where one or both of these constraints cause problems, usually when dealing with external (user or file) input.

For example, we may want to use a string to hold someone’s name, but we do not know how long their name is until they enter it. Or we may want to read in a number of records from disk, but we don’t know in advance how many records there are. Or we may be creating a game, with a variable number of monsters (that changes over time as some monsters die and new ones are spawned) trying to kill the player.

If we have to declare the size of everything at compile time, the best we can do is try to make a guess the maximum size of variables we’ll need and hope that’s enough:

This is a poor solution for at least four reasons:

First, it leads to wasted memory if the variables aren’t actually used. For example, if we allocate 25 chars for every name, but names on average are only 12 chars long, we’re using over twice what we really need. Or consider the rendering array above: if a rendering only uses 10,000 polygons, we have 20,000 Polygons worth of memory not being used!

Second, how do we tell which bits of memory are actually used? For strings, it’s easy: a string that starts with a \0 is clearly not being used. But what about monster[24]? Is it alive or dead right now? That necessitates having some way to tell active from inactive items, which adds complexity and can use up additional memory.

Third, most normal variables (including fixed arrays) are allocated in a portion of memory called the stack. The amount of stack memory for a program is generally quite small -- Visual Studio defaults the stack size to 1MB. If you exceed this number, stack overflow will result, and the operating system will probably close down the program.

On Visual Studio, you can see this happen when running this program:

Being limited to just 1MB of memory would be problematic for many programs, especially those that deal with graphics.

Fourth, and most importantly, it can lead to artificial limitations and/or array overflows. What happens when the user tries to read in 600 records from disk, but we’ve only allocated memory for a maximum of 500 records? Either we have to give the user an error, only read the 500 records, or (in the worst case where we don’t handle this case at all) overflow the record array and watch something bad happen.

Fortunately, these problems are easily addressed via dynamic memory allocation. Dynamic memory allocation is a way for running programs to request memory from the operating system when needed. This memory does not come from the program’s limited stack memory -- instead, it is allocated from a much larger pool of memory managed by the operating system called the heap. On modern machines, the heap can be gigabytes in size.

Dynamically allocating single variables

To allocate a single variable dynamically, we use the scalar (non-array) form of the new operator:

In the above case, we’re requesting an integer’s worth of memory from the operating system. The new operator returns a pointer containing the address of the memory that has been allocated.

Most often, we’ll assign the return value to our own pointer variable so we can access the allocated memory later.

We can then dereference the pointer to access the memory:

If it wasn’t before, it should now be clear at least one case in which pointers are useful. Without a pointer to hold the address of the memory that was just allocated, we’d have no way to access the memory that was just allocated for us!

How does dynamic memory allocation work?

Your computer has memory (probably lots of it) that is available for applications to use. When you run an application, your operating system loads the application into some of that memory. This memory used by your application is divided into different areas, each of which serves a different purpose. One area contains your code. Another area is used for normal operations (keeping track of which functions were called, creating and destroying global and local variables, etc…). We’ll talk more about those later. However, much of the memory available just sits there, waiting to be handed out to programs that request it.

When you dynamically allocate memory, you’re asking the operating system to reserve some of that memory for your program’s use. If it can fulfill this request, it will return the address of that memory to your application. From that point forward, your application can use this memory as it wishes. When your application is done with the memory, it can return the memory back to the operating system to be given to another program.

Unlike static or automatic memory, the program itself is responsible for requesting and disposing of dynamically allocated memory.

Initializing a dynamically allocated variable

When you dynamically allocate a variable, you can also initialize it via direct initialization or uniform initialization (in C++11):

Deleting single variables

When we are done with a dynamically allocated variable, we need to explicitly tell C++ to free the memory for reuse. For single variables, this is done via the scalar (non-array) form of the delete operator:

What does it mean to delete memory?

The delete operator does not actually delete anything. It simply returns the memory being pointed to back to the operating system. The operating system is then free to reassign that memory to another application (or to this application again later).

Although it looks like we’re deleting a variable, this is not the case! The pointer variable still has the same scope as before, and can be assigned a new value just like any other variable.

Note that deleting a pointer that is not pointing to dynamically allocated memory may cause bad things to happen.

Dangling pointers

C++ does not make any guarantees about what will happen to the contents of deallocated memory, or to the value of the pointer being deleted. In most cases, the memory returned to the operating system will contain the same values it had before it was returned, and the pointer will be left pointing to the now deallocated memory.

A pointer that is pointing to deallocated memory is called a dangling pointer. Dereferencing or deleting a dangling pointer will lead to undefined behavior. Consider the following program:

In the above program, the value of 7 that was previously assigned to the allocated memory will probably still be there, but it’s possible that the value at that memory address could have changed. It’s also possible the memory could be allocated to another application (or for the operating system’s own usage), and trying to access that memory will cause the operating system to shut the program down.

Deallocating memory may create multiple dangling pointers. Consider the following example:

Rule: To avoid dangling pointers, after deleting memory, set all pointers pointing to the deleted memory to 0 (or nullptr in C++11).

Operator new can fail

When requesting memory from the operating system, in rare circumstances, the operating system may not have any memory to grant the request with.

By default, if new fails, a bad_alloc exception is thrown. If this exception isn’t properly handled (and it won’t be, since we haven’t covered exceptions or exception handling yet), the program will simply terminate (crash) with an unhandled exception error.

In many cases, having new throw an exception (or having your program crash) is undesirable, so there’s an alternate form of new that can be used instead to tell new to return a null pointer if memory can’t be allocated. This is done by adding the constant std::nothrow between the new keyword and the allocation type:

In the above example, if new fails to allocate memory, it will return a null pointer instead of the address of the allocated memory.

Note that if you then attempt to dereference this memory, your program will crash. Consequently, the best practice is to check all memory requests to ensure they actually succeeded before using the allocated memory.

Because asking new for memory only fails rarely (and almost never in a dev environment), it’s common to forget to do this check!

Null pointers and dynamic memory allocation

Null pointers (pointers set to address 0 or nullptr) are particularly useful when dealing with dynamic memory allocation. In the context of dynamic memory allocation, a null pointer basically says “no memory has been allocated to this pointer”. This allows us to do things like conditionally allocate memory:

Deleting a null pointer has no effect. Thus, there is no need for the following:

Instead, you can just write:

If ptr is non-null, the dynamically allocated variable will be deleted. If it is null, nothing will happen.

Memory leaks

Dynamically allocated memory effectively has no scope. That is, it stays allocated until it is explicitly deallocated or until the program ends (and the operating system cleans it up, assuming your operating system does that). However, the pointers used to hold dynamically allocated memory addresses follow the scoping rules of normal variables. This mismatch can create interesting problems.
Consider the following function:

This function allocates an integer dynamically, but never frees it using delete. Because pointers follow all of the same rules as normal variables, when the function ends, ptr will go out of scope. Because ptr is the only variable holding the address of the dynamically allocated integer, when ptr is destroyed there are no more references to the dynamically allocated memory. This is called a memory leak. As a result, the dynamically allocated integer can not be deleted, and thus can not be reallocated or reused while the program is running. Memory leaks eat up free memory while the program is running, making less memory available not only to this program, but to other programs as well. Programs with severe memory leak problems can eat all the available memory, causing the entire machine to run slowly or even crash.

Memory leaks can also result if the pointer holding the address of the dynamically allocated memory is reassigned to another value:

It is also possible to get a memory leak via double-allocation:

The address returned from the second allocation overwrites the address of the first allocation. Consequently, the first allocation becomes a memory leak!

Conclusion

Operators new and delete allow us to dynamically allocate single variables for our programs.

Dynamically allocated memory has no scope and will stay allocated until you deallocate it or the program terminates.

Be careful not to dereference dangling or null pointers.

In the next lesson, we’ll take a look at using new and delete to allocate and delete arrays.

6.9a -- Dynamically allocating arrays
Index
6.8b -- C-style string symbolic constants

120 comments to 6.9 — Dynamic memory allocation with new and delete

  • sergk

    New C++ programmers should be notified that there is a fundamental design flaw in C++ (and perhaps any language, allowing explicitly freeing memory) - there is no way to set to null all pointers referencing same memory address, other than knowing/remembering them. Which is affected by “human factors”, and thus can not be reliable. Thats where reference counting and garbage collectors comes in…

    • That is a great point, Sergk. Thanks for bringing it up.

      What Sergk is talking about is the fact that you can have multiple pointers pointing to the same bit of dynamically allocated memory. Let’s say you do something like this:

      Now both pointers point to the dynamically allocated memory. However, if you do this:

      pnPtr2 is left pointing to deallocated memory! And thus a call like this:

      will cause your program to crash, even though it seems like it should be okay.

      There are various technique for getting around this behavior (as mentioned, reference counting and garbage collection), some of which C++ support and some of which it doesn’t. From a coding standpoint, perhaps the best solution is simply to avoid having multiple pointers to the same bit of memory, though this isn’t always reasonable.

      • sergk

        If by “some of which C++ support and some of which it doesn’t” you mean GC, well in C/C++ you can write what ever you want. In theory. but speaking of Garbage Collectors there is number of them for C++, most widely known (IMHO) is Boehm-Demers-Weiser GC (http://hpl.hp.com/personal/Hans_Boehm/gc/)

  • Renu

    1 “Null pointers (pointers set to address 0) ….”
    Cant 0 be address of any memory location?

    2 int nSize = 12; int *pnArray = new int[nSize]; [4] = 7; delete[] pnArray;

    Why is subscript not required in delete?
    like
    delete[nSize] pnArray;

    3 Typo-
    This allows “us to us to” do things like conditionally allocate memory:

    Thanks,
    Renu

    • 1) 0 could be a valid memory location on some systems. However, in C++, assigning 0 to a pointer makes it a null pointer. C++ doesn’t specify that that assigning 0 to a pointer requires the pointer to point to memory address 0 -- a compiler could give it a different bit pattern.

      But in practice, 0 is rarely addressable, and even if it were, the loss of one memory address is likely to be negligible in most cases.

      2) When you use the array version of new, the compiler stores some meta-information about the array size, so that when that location is deleted, it can figure out how much to delete.

      Forcing the programmer to specify that amount would be redundant and lead to overspecification errors (eg. what if the programmer allocated 10 bytes but then tried to delete 8?)

      3) Thanks, I’ll get that fixed.

  • Ben

    When we want to deallocate a pointer

    Can’t we just say:

    Plus, I didn’t understand you answer to the previous comment. ‘Cause if I do

    They point to the same destination and give me the same dereference.

    • It’s the delete keyword that does the deallocation, not the setting to 0. If you set a pointer to 0, the memory originally allocated will be lost forever (well, until the program is cleaned up by the operating system), unless you have another pointer pointing to it. I make a habit of setting my deleted pointers to 0 because having a pointer to deallocated memory can and usually does lead to problems as well.

      If you do int *pnValue2 = pnValue, then pnValue2 and pnValue both point to the same address, and they should give you the same dereference because the dereference of a pointer is just the value at the address the pointer is pointing to. Now, if you delete pnValue or pnValue2, the address that BOTH point to is deallocated. From that point forward, if you use either one while they point to deallocated memory, you’ll be in trouble. One common mistake C++ newbies make is to delete pnValue and set it to 0, and forget that pnValue2 points to the same deallocated location. Then, when they try to access pnValue2, their program crashes.

      • sonal gupta

        but when you set pnvalue to 0 and knowing that pnvalue2 is pointing to the same address as that of pnvalue..why dont pnvalue2 also shows 0 as its address just like pnvalue?

        • Alex

          Remember that pnValue and pnValue2 are separate variables. Because they are are pointers, each variable holds an address (we say the pointer is pointing to this address).

          When we do pnValue=0, we’re setting pnValue’s value (the address it is pointing to) to 0. This does not affect pnValue2, which is still holding the address it originally had.

  • SapphireRyoko

    Hi Alex 😀 First I want to say I love your tutorials! I have a question:

    I want to create a variable to store someone’s name in. Like you mentioned at the beginning of this lesson, we don’t know how many characters their name is until they enter it. The problem is that cin (as far as I know) requires variables to be declared ahead of time, but when declaring an array, you have to specify its size right away! Is it possible to work around this problem (without asking how many characters their name is first) using what I’ve learned up to this lesson, or will I need to wait until a later lesson for that?

  • afds

    Doesn’t the memory leak only last until the program ends? … after you close the program… the memory is free again?

    • Most modern operating systems will clean up for you when the program exits.

      That said, it’s not a good idea to rely on the OS to do this for you. This is less true when doing little sample programs, but once you start writing larger programs having lots of memory leaks can really bog down your entire system, especially if you’re not running on much memory.

  • Spock

    …maybe something like the following example:

    Code effectively allows the user to define the arrays size while the program is running.

  • OTS

    THANKS ALEX FOR ALL THE HARD WORK.

    But i am having a hard time getting this to work; I seems once the pointer has been allocated memory to Null(0) u cannot store any value to it (*ptr =5 wont work) unless u reassign new address ptr = &someAddress.

    • This is correct. Remember that a pointer stores an address, and when you dereference a pointer, it gets the value at that address. Thus, if you store the address of 0 in a pointer, when you dereference it, it tries to get the value at address 0. This is generally protected memory and will cause your OS to crash or throw an exception.

      If you want to get or set a value via pointer, the pointer has to point to allocated, valid memory.

  • chkwa

    after deleting do i need to set the address to 0 of dynamically allocating array or just the dynamically allocating single variable only? or both need to set to 0 address?

  • can u please add more quizes on these subjects alex?

    thx.

  • george

    Interestingly, when I assign a fixed physical adress to a pointer, for example like this:

    and then I assign a value:

    It compiles without warnings, but it does not actually assign the value to the cell with adress (0x00345D45). Instead, when printing to the console the value referenced by p instead of ‘8’ I get something like -55634323. It seems pointers can operate on memory only when the memory location has been named (through a variable declaration), or when it is dynamically allocated.

  • Sijo

    Alex, Thanks for the great tutorial. But the above code is working fine in my Visual Studio 2005 without crashing. Please explain.

    • Alex

      The results from accessing deallocated memory are undefined. You may find the same value you left there. You may find a different value. Or your program may crash. There are lots of variables in play that determine which scenario you get, few of which you control, so you shouldn’t rely on any particular behavior.

  • SWEngineer

    Simple well explained tutorial.

    Thanks.

  • Konda

    Hello, I have a question: Due to memory leaks on dynamically allocated variable reassignment, does this mean they should be treated like constants? Or is there an effective way to reassign the variable without memory leaks?

  • abhi4556

    what is wrong in this code?
    its giving run time error
    #include
    using namespace std;
    int main()
    {
    int y=4;
    int *x=new int;
    x=&y;
    cout<<"val of y::"<<y;
    delete x;
    return 0;
    }

  • Tyrone

    Good evening,

    I’m having a hard time understanding why the syntax is set up as it is for new. Having int on both sides of the line: “int *pnValue = new int;,” seems redundant. Is there a situation where the data type could be different on one side? Are things set up this way because the pointer pnValue is on the stack?

    • Alex

      It’s redundant because you’re combining two separate things into one line:
      1) On the left, you’re defining a new pointer, which needs to have a type.
      2) On the right, you’re making a dynamic memory allocation request, which also needs to have a type.

      There are cases where the variable on the left has a different type than the memory allocated on the right when dealing with class inheritance and virtual functions.

      But most often, they’ll be the same.

      In C++11, you could make the type on the left auto, and use implicit type deduction:

  • Odgarig

    Hey, Alex.First of all thank you for the great tutorials.
    I’m having trouble with my code below.I think it’s not that complicated though i can’t handle it.Could you please help me?You can skip my code and jump into my question below of my code.I think its so obvious that you can skip the code.Though I have added comments to my code.

    #define _CRT_SECURE_NO_WARNINGS
    #include<iostream>
    #include<string.h>
    #include<stdlib.h>
    #include <stdio.h>
    char *ptr[2000];
    using namespace std;
    int  main()
    {
        FILE *opener;
        opener = fopen("input.txt", "a");
        int n=7, m=0;
        for (int j=0;j<500;j++)
         {
            ptr[j] = new char[20];// HERE I ALLOCATE MEMORY TO FIRST 500 ELEMENT
            
         }
        int answer;
        int a=0,b=1;
        for(int i=a;i<b;i++)//HERE WE GETS STRINGS FOR PTR[J].
        {
    //HERE *PTR GETS STRING FOR PTR[i].i EQUALS 0.(MY PROBLEM TAKING PLACE HERE.BUT FOR NOW IGNORE THIS)
        cout << "Enter name: "; fgets(ptr[i], 20, stdin); fputs(ptr[i], opener); cout<<"i="<<i<<endl;

    //HERE *PTR GETS STRING FOR PTR[++i].i EQUALS 1.AND THE REST WILL BE INCREASING BY 1 AS YOU CAN SEE.
        cout << "Enter group: " ; fgets(ptr[++i], 20, stdin); fputs(ptr[i], opener);cout<<"i="<<i<<endl;

        cout << "Enter fac: "; fgets(ptr[++i], 20, stdin); fputs(ptr[i], opener);cout<<"i="<<i<<endl;
        cout << "Enter course: "; fgets(ptr[++i], 20, stdin); fputs(ptr[i], opener);cout<<"i="<<i<<endl;
        cout << "Enter number: "; fgets(ptr[++i], 20, stdin); fputs(ptr[i], opener);cout<<"i="<<i<<endl;

    //HERE *PTR GETS STRING FOR PTR[5].
        cout << "Enter grade: "; fgets(ptr[++i], 20, stdin); fputs(ptr[i], opener);cout<<"i="<<i<<endl;
            

    cout<<"Do you want to add information? ";//HERE I ASK USER TO ADD MORE INFORMATION.IF USER WANTS TO ADD
                                             //MORE INFORMATION THEN WE WILL CHANGE OUR LOOP CONDITION
                                             //INTO GIVING A STRING FOR NEXT ELEMENT OF PTR[].WHICH FOR PTR[6]
            cin>>answer;//WE WILL ADD MORE INFORMATION.
            if(answer==1)
            {
               {    a=a+1;//HERE i EQUALS NEXT ELEMENT OF PTR[] WHICH IS PTR[6].a EQUALS i.
                b=b+1;//HERE b EQUALS b+1 FOR LOOP i<b SO THAT CONDITION IS CORRECT FOR NEXT LOOP.
               }
            }
            else{}
        }
        fclose(opener);
        delete[] ptr[2000];
    return 0;
        
    }
    Problem is that after compiling a program first loop works perfectly fine and displays what they should.And when program asks user to add more information after answering yes(by entering 1) it skips ptr[6],jumps into ptr[7] which will display "Enter group: ".And rest is same.Any answer would be appreciate.

  • Connor

    Hello Alex, I’m having trouble understanding the deletion of pointers.
    I understand that:

    will free up the allocated memory but keep the address. But, doesn’t setting

    set the address itself to zero. doesn’t this ultimately destroy pnValue as a pointer because it now points to 0 instead of the initial adress. Intuitively, one would think we want to write instead

    Thanks again for this tutorial, it’s all I’m using to learn C++. I hope you have an awesome 4-July.

    • C++ newbie

      ok so say you do something like this

      This is how I understand it.  When the space is 4 bytes and empty, the space is essentially 00000000 00000000 00000000 00000000.  These are 4 bytes that you won’t be using anymore, so instead of just leaving them there to take up space, you might as well get rid of them by telling the pointer to be assigned to the memory address 0, which is NULL.

      • Connor

        So 0 is just slightly more efficient than typing null, but both mean the same thing?

        Is this why when I try to set

        I get an error?

        On that note, why can’t  I define a specific adress i.e.

        Thanks.

        • C++ newbie

          Yea I think pnValue = 0 and pnValue = null are interchangeable.  I really had no idea why pnValue = 1 or pnValue = 0x127cd6a wouldn’t work so I looked it up StackOverflow.  Apparently pointers are immutable, unless you do something special with them.

          This was the answer given on StackOverflow.  If you want a pointer to point somewhere specific, you need to use a cast on it.  I don’t know if I can explain further than that since I’m a C++ newbie.  This stuff is pretty much way over my head since I kind of just skimmed over the chapter about pointers-it’s pretty confusing stuff, especially for a newbie like me.

    • Alex

      Setting a pointer to 0 tells the compiler that the pointer should now be treated as a null pointer. This doesn’t “destroy the pointer”, it just means that right now, the pointer isn’t pointing at anything. You can always assign another address to it:

  • Shivam Tripathi

    Alex…i hv a question…suppose i hv two different blocks in a program and i also know that any variable defined in one block can’t be used in other coz of the "scope" rules and "non-visibility" rules..but suppose i wanna use the variable from one block in other..so can i define a pointer-variable in that second block and store the address of the variable which is in the first block and then access it by De-referencing that pointer…i mean :

    I just wanna knw "Is that legal"???

    • Alex

      ptr = &a; won’t even compile, because the block that ptr is in can’t see variable a from the other block. It’ll give you an error about an unknown identifier.

  • Shivam Tripathi

    Yeah…I also expected the same!!!….but actually it compiled and gave me the output…yet there was only a warning : " address of local variable ‘a’ returned "…

    I went thru d definition of "Scope" in more depth…It states that " Scope of any variable validates the name-binding ..i.e the relation of the object with the identifier…so may be it means that after the end of the scope u " can’t access any variable value with it’s name with which it was declared inside that block"…that object or value may be present at that memory location ….just the relationship b/w a value and it’s NAME has been end…that’s why accessing that memory location, i got the value…Am i right???

    • Alex

      It depends. Dynamically allocated memory has no scope, so if you keep a pointer to it, you can access it later and whatever was in memory will still be there.

      But in your sample program above, a is a local variable. a is given memory when the block starts and it dies at the end of the block. If the block is executed again, a will be recreated, possibly at a different location. It doesn’t have a persistent location.

      In your code, ptr = &a is simply nonsensical, because you can’t take the memory address of something that doesn’t exist!

  • saikiran

    here i am trying to o/p the values present in the array,that are accepted during runtime,onto the console. but when i run this program i get the 5 values in the array as the last value only.
    for ex: if i give 0 1 2 3 4 as the five values for this program then the o/p is shown as
    4 4 4 4 4 . Can anyone help me out with this problem please?

    #include "stdafx.h"
    #include<iostream>
    using namespace std;

    int main()
    {
        int arrsize = 5;
        int *ptr = new int[arrsize];
        *ptr = 7;
        cout << *ptr << endl;
        cout << "enter 5 values:";
        for (int i = 0; i < arrsize; i++)
        {
            
            cin >> *ptr;
            
            cin.get();
        }

        cout << "the values in the array are:\n ";
        for (int i = 0; i < arrsize; i++)
        {
            cout << *ptr << " ";

        }
        delete[] ptr;
        cin.get();
        return 0;
    }

    • Alex

      ptr always points to the first element of the array, so *ptr always translates to the value of the first element of the array.

      You’re not actually iterating over your array, you’re just putting values into the first element and reading them back out.

      Instead of *ptr, you should be using ptr[i] inside the loops above.

  • Ardit

    Hi Alex,
    thanks for your tutorial its great.
    i had one question about memory leaks.
    Memory leaks exist only when the program runs and are deleted after the program ends or they are there even after the program has endet?

    • Alex

      Most modern operating systems will generally clean up after applications have terminated, precisely to avoid issues with memory leaks affecting system stability. However, some older operating systems or specialized operating systems don’t do this.

      That said, programs that leak memory can end up using a significant amount of memory if they run for a while. I’ve seen leaky games use up gigs of memory before they crashed (probably due to running out of memory).

  • Daniel

    Hey Alex, I have been following this tutorial for a few months at my own pace and I just wanted to thank you so much for all that you are doing.
    Just one question about this page, you said:

    "Keep in mind that just like normal variables, when a pointer is created, it’s value is undefined. Consequently, it is a good idea to set all pointers that are not used right away to 0:"

    Is this for all pointers, or just pointers that are defined without the "new" keyword?

  • Naga Pushkal

    Hi Alex, The following code is working fine for me in Visual Studio 2010. But I am unable to come up with the reason why it is giving an output instead of getting crashed. Could you please help me out with this?

    int main()
    {
       int *pnPtr = new int;
       delete pnPtr;
       *pnPtr = 4;
       cout << *pnPtr << endl;

       return 0;
    }

  • "it deletes the memory that the pointer points to!"
    I think this line should be "it deletes the content of the memory that the pointer points to!"
    Please let me know if I am wrong:

    This program prints the memory address that pointer points to, and the content of that address. Even after deleting the dynamically allocated variable, address remains same and I can assign a new value to it. "IS THAT DANGEROUS?"

    • Alex

      Yes, it’s dangerous. Accessing deleted memory or trying to delete it again results in undefined behavior, which would manifest as incorrect results or an application crash.

      (I’ll fix the typo when I rewrite the lesson -- working on that now!)

  • This program is missing opening quotes in 4th line:

    In the same program, if new fails to allocate memory, it is assigned to null(0) and that’s why program executes the if statement, right?

  • Rajender

    Thank u for wonderful tutorials
    I think there’s a Typo error. Instead of:
        int otherPtr = ptr; // otherPtr is now pointed at that same memory location
    it should be
        int *otherPtr = ptr; // otherPtr is now pointed at that same memory location

  • R4Z3R

    Hi Alex,
    -what is the alternative command of `new` in C programming language?
    -how can we create an array with user input size ?

  • Len

    Hi Alex,
    1) What if the memory contains i.e. a password, if you just pass the address back to the os can’t another program potentially read the value?  Is is safer to clear the value first?

    2) Why can I still reference the ptr after deletion?  I know it is still in scope, but it seems I would want to set the pointer to null first and then delete it.  Does order matter?

    • Alex

      1) Yes, if the data is sensitive, it would make sense to clear it first.

      Even better, don’t ever save passwords in plain text in memory, a file, or a database in the first place. Security-conscious programmers will often either hash the password (use an algorithm to convert it from plain text into gibberish) or trade it in for an access token that can’t be reversed back to the original password.

      2) Just to make sure it’s clear, when you delete a pointer, you’re not deleting the variable itself. You’re deallocating the memory that the variable points to.

      > Why can I still reference the ptr after deletion? I know it is still in scope

      You answered your own question. You can access the variable because it’s still in scope. Deallocating the memory being pointed to doesn’t change the variable’s scope.

      > it seems I would want to set the pointer to null first and then delete it. Does order matter?

      Yes. If you set the pointer to null first, you won’t be able to delete the memory because you don’t have anything pointing to it! You need to deallocate the memory first, and then set the pointer to null (to ensure the deallocated memory isn’t accessed) or another valid value.

  • Luke

    Fantastic lesson, just a little typo here:

    "When requesting memory from the operating system, in rare circumstances, the operating may not have any memory to grant the request with."

    Did you mean to say: "the operating system may not have any memory", instead of "operating may not"?

  • Ankit

    does the pointer gets deleted automatically when it goes out of scope.if not what are the ways to do so(automatically), I usually forget to delete the pointer after using it. does any concept of smart pointer helps?? or to be specific unique pointer/shared pointer/weak pointer.

    • Devashish

      Pointer automatically get deleted when goes out of scope, just like a normal variable. Dynamically allocated memory is not automatically deallocated when goes out of scope. Consider this:

      The pointer to int, named ptr, is the only object that has access to the dynamically allocated memory. Pointer are just variables that points to other variables of the same data type, thus follow the same scoping rules. Dynamically allocated memory is a piece of memory that doesn’t know about its scope and will exist until explicitly deallocated. When function foo exits (e.g. finishes execution), the only reference to the dynamically allocated memory (that is ptr) goes out of scope. A memory leak occurs. Note that you can’t (and you don’t need to) delete a pointer. Yes, smart pointers are smart and do memory managements itself (without user’s interference). Shared pointer allows multiple pointers to point to the same object. unique pointers can’t do this. Smart pointers are implemented as part of C++11 standard (I am not sure about this), thus won’t work in older compilers.

      • Alex

        No, pointers do _not_ get deleted automatically when they go out of scope. Keep in mind that the term “delete” refers to the process of returning allocated memory to the operating system. It does not refer to variables being destroyed when they go out of scope.

        The standard library does contain functionality to help with this in the form of smart pointers that will delete themselves when they go out of scope. See std::unique_ptr, std::shared_ptr, and std::weak_ptr for more information.

        Writing some lessons for these is on my to-do list.

        • Devashish

          Hey Alex,thanks for your reply, but this one confuses me. Take the example again from my previous comment. Is’t ptr getting destroyed when foo’s block exits. Yes, dynamically allocated memory is being leaked, but isn’t the pointer ptr following the automatic duration scoping rules??? We deallocate memory using delete, and do not delete pointers, right? By saying “pointer get deleted when go out of scope”, I mean that pointers follow normal scoping rules. They get deleted (destroyed) when go out of scope, leaving the allocated memory alive in the heap. Am I missing something.

          • Alex

            At this point we’re just quibbling over vocabulary: destroyed vs deleted.

            Deleted has a very specific meaning in C++, in that it refers to the process of deallocating memory. When an automatic (local) type variable goes out of scope, it is _destroyed_, but it is not _deleted_.

            > By saying “pointer get deleted when go out of scope”, I mean that pointers follow normal scoping rules

            They do follow normal scoping rules, and saying that is fine. But by saying pointers get _deleted_ when they go out of scope, it’s easy to misunderstand what you mean and infer that any memory being pointed to is deallocated. This does not happen. Consequently, it’s not correct to say an automatic variable is deleted when it goes out of scope. It isn’t. It’s simply destroyed. 🙂

  • EML

    Hi Alex,

    Thanks for this great tutorial.

    I am trying to understand the delete operator closer to the system level.
    By the description it sounds like all delete should do is flip some bit flag that changes how that memory location is handled and the address stored in ptr should be unaffected by the delete operator.
    But when I run…

    the output on my machine is :
    …00454FC0
    …00008123

    After passing ptr as the argument to the delete operator it now holds a different memory address. I am concerned that I am missing something… I understand this doesn’t affect implementation since the original address contains garbage now but where is this new address coming from?

    Thanks for your help!

  • Georgios Leandros Κυριαζης

    I need some clarification in the nullptr. is it wise to initialize pointers using the nullptr? for example is wise/ok/right/wrong to have a contstructor like bellow

    or would it be better to do like this

    is there a meaningful difference between the two?

    Or should I only use the nullptr to deallocate memory.

    • Alex

      nullptr is the C++11 replacement for using 0 as a null pointer. Using nullptr is slightly better than using 0, as it makes your intent clearer and this can help avoid ambiguities in certain cases.

  • Roee Sefi

    Hi Alex
    As far as i know,  the c++ standard says that when new operator fails, it throws std::bad_alloc exception (unless being told not to with "no throw").
    The returned null pointer was just De-Facto outcome from old unstandardized compilers

  • Sean Kelly

    In the lesson should:

    Be

    Unless this is a way to handle exceptions?

  • George

    Dear Alex I might be a bit confused about pointers!
    in this lesson, you put a value to an allocated memory like this:

    int *ptr = new int; // allocate memory and put address in ptr
    *ptr = 5; // put a value in that memory

    I allocated memory for an array but without the asterisk:

        int *array = NULL;
        array = new int[1000000];
    How do you explain this?
    How can I do the same without specifying the array’s size?

    • Alex

      Could be rewritten as:

      Which you can see is analogous to how we allocated memory for a single int.

      When we dynamically allocate memory (whether for a single value or an array), the operating system returns an address to the allocated memory. We store that address in variable ptr (or array, in the array case).
      Now, to access that memory, we need to dereference the pointer. For a single value, we use operator*: e.g. *ptr = 5; For arrays, we can use either operator* (to access the first element of the array), e.g. *array = 5; or the subscript operator[], e.g. array[3] = 5.

      Does that make sense? If not, where are you still confused?

  • Phuong H Tran

    I like your profile pic, Alex. the cat’s face is hilarious. Haha.

  • Aditya

    Firstly great tutorial.Excellent work.

    In dynamically allocating single variables you have done

    however *ptr is a pointer.
    So how can we assign it a value?

    In chapter 6.7 you have clearly stated that we must assign address

    So which is correct or are both of them correct? I am totally unable to get my mind around this.
    Thanks in advance

    • Alex

      In this context, * is acting as a dereference, so *ptr means “the value at the address of ptr”. So we’re assigning the integer value 7 to the value at the address of ptr.

      This would be an invalid syntax (unless ptr is a pointer to a pointer).

      What I actually said was this:

      In this case, * means ptr is a pointer.

      The difference here is in context: * used in a variable declaration means “pointer”, * used otherwise means “dereference”.

  • dex

    Hi Alex,

    In the lesson’s example:

    "Deleting a null pointer has no effect. Thus, there is no need for the following:"

    be

    if we want the if condition evaluates to true and then delete the null pointer?

    Although, as you said it could be done without the condition statement. I am just confused with the logic of the condition.

    Thanks.

    • Kodnot

      The first if statement would be used if we wanted to delete the pointer if it WAS NOT a null pointer. But because deleting a null pointer has no effect (aka it won’t cause problems), there is no need to do so.
      In other words, we want the If to evaluate to true if the pointer does not point to null, not vice versa ^^

    • Alex

      Deleting a null pointer does nothing (it is not harmful). Therefore, there is no need to say:

      Instead we can just say

      Because if ptr is a null pointer, delete ptr will do nothing anyway. So there’s no need to guard against deleting the null pointer (with an if statement).

      This code:

      is completely useless. If ptr is a null pointer, it will delete the null pointer, which does nothing. If ptr is not a null pointer, it will skip the delete statement, doing nothing.

      • dex

        Hi Alex, Kodnot,

        Thanks for clarifying it. actually, I was confused with the intent of this statement:

        "Deleting a null pointer has no effect. Thus, there is no need for the following:"

        Instead we can just say

        I interpreted it the other way around that is why I was then confused with the logic of the code.

  • cei

    There is a typo: one "allocated" is missing a ‘t’.

  • Shiva

    Hey Alex,

    A few suggestions:

    > The new operator returns the address of the variable that has been allocated.
    I believe new returns ‘a pointer containing the address of the variable’ that has been allocated, rather than the address as literal, just like the & operator? If that’s so, you’d better modify the wording to be clear.

    > Without a pointer to hold the memory address of the memory that was just allocated, …
    ‘memory address of the memory’ feels a bit awkward. ‘address of the memory’ would have sufficed. 😀

    Last thing: I read elsewhere that the new operator can also do initialisation of the dynamically allocated memory, like:

    If you haven’t already mentioned it somewhere, isn’t this a point worth including?

    Anyway great lesson, once again. Thanks as always! 🙂

  • Elpidius

    Hi Alex,

    I’m confused with something.

    You wrote:
    "Your computer has memory (probably lots of it) that is available for applications to use. When you run an application, your operating system loads the application into some of that memory. Your application reserves some additional memory for normal operations (keeping track of which functions were called, creating and destroying global and local variables, etc…)."

    Does the application reserve some additional memory from RAM without permission from the Operating System? Or in the third quoted sentence were you meant to say: "From this allocated memory your application reserves some of that memory for normal operations…"

    • Alex

      I rewrote the text in question to (hopefully) be more precise and more understandable. The OS handles the loading of the application into memory and setting up all of the pointers that are used by the application to access the different areas of memory it requires for operation.

  • J3ANP3T3R

    if anyone could help im a bit confused:

    "Note that deleting a pointer that is not pointing to dynamically allocated memory may cause bad things to happen."

    but

    "If ptr is non-null, the dynamically allocated variable will be deleted. If it is null, nothing will happen."

    shouldn’t we need to check if the pointer is not null before we delete it ? or else we get "bad things to happen" ?

    • Alex

      Nope. If your pointer _ever_ points to non-dynamically allocated memory, you’ve already screwed up somewhere and your program is doomed. So let’s assume that can’t happen, because you’d never do that. That means that your pointer is either pointing to dynamically allocated memory, or it’s pointing to null. If it’s pointing to dynamically allocated memory, and you delete it, then great, the memory gets deallocated. If it’s pointing to null and you delete it, then nothing happens, which is fine. In either case, a pre-check for non-null doesn’t provide any additional value.

      In the case where you ARE pointing to non-dynamically allocated memory, or some other garbage value, a null check won’t help you anyway -- the pointer is non-null so it will pass, and then you’ll try and delete it, and your program will probably crash.

  • Nyap

    How can you see the size of the heap on your system

    • Nyap

      also, if you don’t use the "delete" operator to explicitly deallocate a dynamically allocated variable, will that memory be unusable by other programs until you reboot your pc/phone/whatever

    • Alex

      It varies by OS, as well as how much physical memory you have, how much hard drive swap space you have, and how much memory is being used. I’m not aware of any easy way to see how much memory is available on the heap.

  • Alf

    Hi Alex,
    Thanks for your tutorial.
    Do you know how to avoid double-allocation problem you mentioned in the last part? I use a class with a deque pointer member. I may create many deques and let that pointer point to them according to the change of input.

    • Alex

      The easiest way to avoid double allocation is to always make sure you always delete your variables before reallocating.

      You can also use std::unique_ptr from the C++ standard library to help manage the lifetime of your pointers. I’m intending to write lesson on std::unique_ptr soon.

  • Punched Fortran

    Typo, " … overflow the record array and watching something bad happen." should probably read " … overflow the record array and watch something bad happen."
    Thanks for the tutorial!

  • Punched Fortran

    Other typos:
    "Pointers that are pointing to deallocated memory are called dangling pointer" should probably read "Pointers that are pointing to deallocated memory are called dangling pointers" (make second "pointers" plural).
    "Operator new and delete allow us to dynamically allocate …" should probably read "Operators new and delete allow us to dynamically allocate …" (make "Operators" plural).  
    (Sorry -- should have read the whole article first.)  Thanks again for all your work!

  • Akub

    Hi Alex,

    While experimenting with pointers in Visual Studio, I’ve come across something a bit worrying. Maybe you could explain what’s happening and let me know if it’s a bug in the compiler. The following program executes just fine on my computer, but I’m not sure if it’s safe to run.

    For some reason, it lets me assign to *otherPtr, even though the memory is deallocated. Bizarrely, the same is not true for *ptr in the commented out line.

    Also, thanks a lot for your tutorial! It has helped me a great deal.

    • Alex

      Ensuring you don’t access dangling pointers is the responsibility of the programmer, not the compiler. So the fact that you are able to assign to *otherPtr isn’t a bug in the compiler (but it will cause undefined behavior if you try to run the program). Rather, the fact that your Visual Studio appears to be preventing you from compiling “*ptr = 5” just after deleting ptr is an unexpected nicety.

      • Akub

        I see. But since I am allowed to access and change the values pointed to by dangling pointers, does that mean my program could directly interfere with other programs and/or the operating system?

  • Ivar

    Does new differ from just using malloc()? Or is it just a convenience to have it as a keyword? (I’m asking because if you don’t want an exception thrown, writing

    feels more complicated than just doing

    . If you do want an exception at failure new is clearly better!)

    • Alex

      Yes, new is different than malloc(). One key difference is that new will call constructors of classes, whereas malloc will not. In effect, malloc is not class-aware. New is also more type-safe.

      In C++, you should never user malloc(). Always use new.

      • Ivar

        Ah ok, I didn’t think of that. That does make it a lot easier and safer to use with classes.

        If you have time, could you elaborate on how new is more type-safe? (Just curious, you’ve already convinced me to use it..)

        • Alex

          In C++, malloc() returns a void* and you must cast this to whatever type you intended. This leaves a lot of room for errors/silliness. new on the other hand ensures proper type-checking:

  • Ivar

    Btw, I need to #include <new> to get access to std::nothrow (found out from the c++ reference). Maybe you should add that, unless it’s specific to me (I’m using gcc).
    Thanks for a great tutorial!

  • Norton Verde

    Very good and clear explanations revealing a deep and trustable knowledge. Congratulations .I’ll be back frequently !

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter