9.13 — 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 creates the object using that memory, and then 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 perform indirection through 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. Indirection through- 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:

There are a few best practices that can help here.

First, try to avoid having multiple pointers point at the same piece of dynamic memory. If this is not possible, be clear about which pointer “owns” the memory (and is responsible for deleting it) and which are just accessing it.

Second, when you delete a pointer, if that pointer is not going out of scope immediately afterward, set the pointer to 0 (or nullptr in C++11). We’ll talk more about null pointers, and why they are useful in a bit.


Set deleted pointers to 0 (or nullptr in C++11) unless they are going out of scope immediately afterward.

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 indirection through this pointer, undefined behavior will result (most likely, 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 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 normal scoping rules for local 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 variables are just normal variables, when the function ends, ptr will go out of scope. And 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 means the program has now “lost” the address of the dynamically allocated memory. As a result, this dynamically allocated integer can not be deleted.

This is called a memory leak. Memory leaks happen when your program loses the address of some bit of dynamically allocated memory before giving it back to the operating system. When this happens, your program can’t delete the dynamically allocated memory, because it no longer knows where it is. The operating system also can’t use this memory, because that memory is considered to be still in use by your program.

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. Only after your program terminates is the operating system able to clean up and “reclaim” all leaked memory.

Although memory leaks can result from a pointer going out of scope, there are other ways that memory leaks can result. For example, a memory leak can occur if a pointer holding the address of the dynamically allocated memory is assigned another value:

This can be fixed by deleting the pointer before reassigning it:

Relatedly, 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!

Similarly, this can be avoided by ensuring you delete the pointer before reassigning.


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

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

Be careful not to perform indirection through dangling or null pointers.

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

9.14 -- Dynamically allocating arrays
9.12 -- C-style string symbolic constants

343 comments to 9.13 — Dynamic memory allocation with new and delete

  • 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. :)

  • 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"?

  • 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.

  • R4Z3R

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

  • 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

  • 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?

  • "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!)

  • 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;

  • 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?

  • 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).

  • 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"
    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;

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

        delete[] ptr;
        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.

  • 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 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!

  • 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 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.

  • 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.


        • 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:

  • 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.

    #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].
        cout << "Enter name: "; fgets(ptr[i], 20, stdin); fputs(ptr[i], opener); cout<<"i="<<i<<endl;

        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;

        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.
               {    a=a+1;//HERE i EQUALS NEXT ELEMENT OF PTR[] WHICH IS PTR[6].a EQUALS i.
        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.

  • 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:

  • abhi4556

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

  • 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?

  • SWEngineer

    Simple well explained tutorial.


  • 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.

  • 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.

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


  • 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?

  • OTS


    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.

  • Spock

    ...maybe something like the following example:

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

  • 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.

  • SapphireRyoko

    Hi Alex :D 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?

  • 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.

  • 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?
    delete[nSize] pnArray;

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


    • 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.

  • 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 (

Leave a Comment

Put all code inside code tags: [code]your code here[/code]