Navigation



6.9 — Dynamic memory allocation with new and delete

All of the variables used up to this point in the tutorial have one thing in common: the variables must be declared at compile time. This leads to two issues: First, it’s difficult to conditionally declare a variable, outside of putting it in an if statement block (in which case it will go out of scope when the block ends). Second, the size of all arrays must be decided upon in advance of the program being run. For example, the following is not legal:

cout << "How many variables do you want? ";
int nVars;
cin >> nVars;

int anArray[nVars]; // wrong!  The size of the array must be a constant

However, there are many cases where it would be useful to be able to size or resize arrays while the program is being run. 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 chasing 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 number of variables we’ll need and hope that’s enough:

char szName[25]; // let's hope their name is less than 25 chars!
Record asRecordArray[500]; // let's hope there are less than 500 records!
Monster asMonsterArray[20]; // 20 monsters maximum

This is a poor solution for several 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 allocating over twice what we really need! Second, it can lead to artificial limitations and/or buffer overflows. What happens when the user tries to read in 600 records from disk? Because we’ve only allocated 500 spaces, either we have to give the user an error, only read the first 500 records, or (in the worst case where we don’t handle this case at all), we overflow the record buffer and our program crashes.

Fortunately, these problems are easily solved via dynamic memory allocation. Dynamic memory allocation allows us to allocate memory of whatever size we want when we need it.

Dynamically allocating single variables

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

int *pnValue = new int; // dynamically allocate an integer

The new operator returns the address of the variable that has been allocated. This address can be stored in a pointer, and the pointer can then be dereferenced to access the variable.

int *pnValue = new int; // dynamically allocate an integer
*pnValue = 7; // assign 7 to this integer

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

delete pnValue; // unallocate memory assigned to pnValue
pnValue = 0;

Note that the delete operator does not delete the pointer — it deletes the memory that the pointer points to!

Dynamically allocating arrays

Declaring arrays dynamically allows us to choose their size while the program is running. To allocate an array dynamically, we use the array form of new and delete (often called new[] and delete[]):

int nSize = 12;
int *pnArray = new int[nSize]; // note: nSize does not need to be constant!
pnArray[4] = 7;
delete[] pnArray;

Because we are allocating an array, C++ knows that it should use the array version of new instead of the scalar version of new. Essentially, the new[] operator is called, even though the [] isn’t placed next to the new keyword.

When deleting a dynamically allocated array, we have to use the array version of delete, which is delete[]. This tells the CPU that it needs to clean up multiple variables instead of a single variable.

Note that array access is done the same way with dynamically allocated arrays as with normal arrays. While this might look slightly funny, given that pnArray is explicitly declared as a pointer, remember that arrays are really just pointers in C++ anyway.

One of the most common mistakes that new programmers make when dealing with dynamic memory allocation is to use delete instead of delete[] when deleting a dynamically allocated array. Do not do this! Using the scalar version of delete on an array can cause data corruption or other problems.

Memory leaks

Dynamically allocated memory effectively has no scope. That is, it stays allocated until it is explicitly deallocated or until the program ends. However, the pointers used to access dynamically allocated memory follow the scoping rules of normal variables. This mismatch can create interesting problems.

Consider the following function:

void doSomething()
{
    int *pnValue = new int;
}

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, pnValue will go out of scope. Because pnValue is the only variable holding the address of the dynamically allocated integer, when pnValue 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. 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:

int nValue = 5;
int *pnValue = new int;
pnValue = &nValue; // old address lost, memory leak results

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

int *pnValue = new int;
pnValue = new int; // old address lost, memory leak results

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

Null pointers (part II)

Null pointers (pointers set to address 0) are particularly useful when dealing with dynamic memory allocation. A null pointer basically says “no memory has been allocated yet”. This allows us to do things like conditionally allocate memory:

// If pnValue isn't already allocated, allocate it
if (!pnValue)
    pnValue = new int;

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:

int *pnValue = new int;
int *pnOtherValue = 0; // will allocate later

Similarly, when a dynamically allocated variable is deleted, the pointer pointing to it is not zero’d. Consider the following snippet:

int *pnValue = new int;
delete pnValue; // pnValue not set to 0

if (pnValue)
    *pnValue = 5; // will cause a crash

Because pnValue has not been set to 0, the if statement condition evaluates to true, and the program tries to assign 5 to deallocated memory. This almost inevitably will cause a program to crash. It is never a good idea to leave a pointer pointing to deallocated memory. When deallocating memory, set the pointer that has been deallocated to 0 immediately afterward. This helps ensure the program does not try and access memory that has already been deallocated. The above program should be written as:

int *pnValue = new int;
*pnValue = 7;
delete pnValue;
pnValue = 0;

if (pnValue)
    *pnValue = 5;

Get in the habit of assigning your pointers to 0 both when they are declared (unless assigned to another address), and after they are deleted. It will save you a lot of grief.

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

if (pnValue)
    delete pnValue;

Instead, you can just write:

delete pnValue;

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

6.10 — Pointers and const
Index
6.8 — Pointers, arrays, and pointer arithmetic

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

    int *pnPtr1 = new int;
    int *pnPtr2 = pnPtr1;
    

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

    delete pnPtr1;
    pnPtr1 = 0;
    

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

    if (pnPtr2)
        *pnPtr2 = 5;
    

    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) Each “chunk” of memory has to have a unique address, otherwise there’d be no way to address that chunk of memory individually. On the 80×86 architecture, the size of that “chunk” is a byte, which means we can address individual bytes. The address of 0 is used to mean “not pointing to anything”.

      2) My understanding is that the program/memory system keeps track of how large your arrays are (I am not sure how this happens behind the scenes). In any case, when you delete the array, it already knows 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.

  • Abdul

    In making class Biginteger how we can use dynamic memory allocation

  • Petter

    I’m working on an assignment for a course I’m taking and we are to create two classes; Vertex and Polygon, with the Polygon class consisting of an array of Vertices. The array of Vertices is dynamically allocated, and I have two constructors:

    class Polygon {
    
        private:
            Vertex* vertices;
            int numVerts;
        public:
    
            //Constructors
            Polygon(Vertex vert[], int numVerts){
                vertices = vert;
                this->numVerts = numVerts;
            }
    
            Polygon() {
                vertices = 0;
                numVerts = 0;
            }
    ...
    

    The parameterless constructor thus creates an “empty” Polygon. There is however a function add() with which you can add a Vertex to the Polygon. I have written it like this:

    void add(Vertex newVert) {
    
       Vertex* tmp = new Vertex[numVerts+1];
       if(vertices) {
          tmp = vertices;
          delete[] vertices;
       }
       tmp[numVerts] = newVert;
       vertices = new Vertex[++numVerts];
       vertices = tmp;
       delete[] tmp;
    
    }

    But if a create a Polygon with the default constructor and then add three Vertices the program crashes. The weird thing though is that the crash doesn’t seem to come until I have come to the last line (delete[] tmp;), but only when I add the third Vertex. The firs two go fine. Any ideas as to why this happens?

    Thanks!

    /P

    • I see a couple of things done incorrectly here. First, in your constructor, you assign vertices = vert; You seem to be assuming this will copy the incoming elements, but it won’t. It’ll simply set vertices to point to those elements.

      This is asking for trouble. If the user passes in a non-dynamically allocated vertex array, you will end up with the vertex pointer pointing to a local variable that will eventually go out of scope. When it does, and you try to access it, you program will crash.

      Instead, it is safer to allocate a new dynamic vertex array inside your constructor and then copy the vertices to it individually (using a for loop). This way you can guarantee that your vertices will persist even if the user passes in vertices that have been non-dynamically allocated.

      Second, to see why Add() crashes, simply step through your code when vertices is non-null (which it is when you’ve called the above constructor):

      In this case, the if condition is true, so the conditional executes. tmp is set to vertices. Because tmp and vertices are both pointers, this simply does a pointer assignment. It does not copy the vertices! So when you delete vertices, you also delete what tmp is pointing to. Consequently, after the conditional, tmp is pointing to garbage. tmp[numVerts] = newVert tries to write a vertex into unallocated memory. Then later, you delete tmp, which is already pointing to unallocated memory. Trying to delete unallocated memory will always crash your program.

      You basically have the right idea, you’ve just assumed that assigning one pointer to another will copy the elements, and it won’t. It’ll just make them point to the same thing.

      Your add function should look like this:

      void add(Vertex newVert)
      {
         Vertex* tmp = new Vertex[numVerts+1];
         if(vertices) {
      // copy your old vertices into temp.  This will involve using a for loop
      // and copying them individually
            delete[] vertices;
         }
         tmp[numVerts] = newVert;
         vertices = new Vertex[++numVerts]; // you don't need this
         vertices = tmp;
         delete[] tmp; // or this
      
      // increment numVerts here
      }
      

      This way, you allocate a new temp array, copy elements from the old array to the new array, delete the old array, and then set the old array to point to the new one.

  • [...] 2007 Prev/Next Posts « 6.7 — Introduction to pointers | Home | 6.9 — Dynamic memory allocation with new and delete » Wednesday, July 11th, 2007 at 6:20 [...]

  • Ben

    When we want to deallocate a pointer

    delete pnValue;
    pnValue = 0;

    Can’t we just say:

    pnValue = 0;

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

    int *pnValue2 = pnValue;

    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.

  • som shekhar

    deleting a variable twice will also cause crash.

    int *ptr = new int;
    delete ptr;
    delete ptr;
    
  • Frank

    I don’t know if this is the right place for this question but I can’t find another section that
    deals with what I want to know.
    In ‘C’ you can create an array of “unknown size” using initialization, essentially getting the
    compiler to count the memebers.

    const int myarray[] = { 1, 2, 3 };

    What’s the best way to do this in C++?
    Would I put this line in the class definition? Seems to me that not the right way to do it.
    I think it should be a job for the constructor. But then you would need to know the array size
    when you declared the array. Am I doing this the right way? or is there a better way?
    My actual example is an array of struct and the initialization is more complex but I don’t want
    to have to count the number of entries. It’s a table I want to be able to grow by adding members
    in the initialization list.

    • There are a couple of options. If you want an array that is shared by all members of your class, you could make the array in your class static and define it in the cpp file just like you do above (see the lesson on static member variables for more info).

      If you want a per-class array, my advice would be to stop using C-style arrays altogether and use std::vector, then push values onto the vector in your class constructor.

      • Frank

        Thanx Alex,
        The array I am talking about is used as a cmd table. So while I expect version 1.0 to support
        a few commands I also expect that future release will support more commands. What I want is a table
        with the command and support routines that people (not necessarily me) can add new commands to the
        bottom of the table. Asking them to remember to bump a size of the table is more than I would like.

        This said, the std::vector gives much more funtionality than I need, as I do not expect the table
        to grow for any given release. It really should be constant for one release.

        I’m still trying to decide if such a table should even be part of the class. All the support routines
        have nothing to do with the module itself… sorta. I have moved it outside the class since I
        first posed the question and now pass it to the object. This is more a question of design now than C++.

        But I have another question on your reply. If I make a class member static, is the scope of that
        variable still within the class? Or does it still make it global for the rest of the file as per C.
        (your right in assuming I’m from the world of C and still a novice in C++).

        • Static members are kind of funny — they’re members of the class, but you don’t need an instantiated class member to access them. You can access it directly via using the class name and the scope operator (eg. MyClass::s_nMyStaticInt). It’s more or less identical to having a global variable inside a namespace, except the class is the “container” for the variable instead of the namespace. Static members are essentially globally scoped.

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

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

      • HORUS793

        Talking about operating systems:
        If I have a virtual machine, and the OS doesn’t handle garbage collectors, would it affect my actual memory?

        Thanks in advance.
        By the way, great tutorials.

  • afds

    How do you find the size of an array with dynamically allocated memory?

    int main()
    {
    	using namespace std;
    	int size;
    	cin >> size;
    	int *anArray = new int[size];
    
    	cout << sizeof(anArray) / sizeof(anArray[0]) << endl;
    	return 0;
    }
    

    This doesn’t work.

    • afds
      int main()
      {
      	using namespace std;
      	int size;
      	cin >> size;
      	int *anArray = new int[size];
      	int sum = 0;
      
      	for (int x = 0; x < size; x++)
      	{
      		sum += sizeof(anArray[x]);
      	}
      	int total_arrays = sum / sizeof(anArray[0]);
      	cout << total_arrays << endl;
      	return 0;
      }
      

      I found a way…but please tell me another way if it is easier.

      • When it comes to dynamically allocated arrays in C++, you have to save the size independently of the array. There’s no way to derive it from the array, unfortunately.

        The sizeof(anArray) / sizeof(anArray[0]) trick only works if anArray is a static array (eg. declared as int anArray[5]).

        Your algorithm doesn’t really work because you loop on the size of the array, which presumes you already know it. If you already know it, there’s no reason to go through the whole process of trying to find it. :)

  • Spock

    …maybe something like the following example:

    #include <iostream>
    
    using namespace std; 
    
    int main()
    {
    
    int* a = NULL;
    int n;
    cin >> n;
    a = new int[n];
    for (int i=0; i<n; i++) {
        a[i] = i*5;
            cout<<endl<<a[i]<<endl;
    }
    
    delete [] a;  // When done, free memory pointed to by a.
    a = NULL;     
    
    }

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

  • Pathik

    How do you dynamically allocate a multidimensional array?

    This does’nt work:

    	int (*anArray) = new int[rows][cols];
    
    • It’s a real pain to do. First allocate an array of pointers to your data type. Then loop through each element of your array and allocate an array from the pointer. Something like this (and forgive me if this is slightly incorrect since I’m doing it from memory:

      int **aanValues = new int*[10];
      for (int nCount=0; nCount < 10; nCount++)
          aanValues[nCount] = new int[10];
      

      An easier way is to allocate a single-dimensional array, and then use a function to index it (again, from memory, so forgive any mistakes):

      int *anValues = new int[nSizeX * nSizeY];
      int getValue(int nX, int nY)
      {
          return anValues[nY * nSizeX + nX];
      }
      
  • 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.

    int *pnValue = new int;
    *pnValue = 7;
    delete pnValue;
    pnValue = 0;   
    
    if (pnValue)
        *pnValue = 5;
    
    • 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?

  • babypinky8888

    Hi

    I am new to pointers. My qn is in the statement followign below..

    int *pnValue = new int; // dynamically allocate an integer
    *pnValue = 7; // assign 7 to this integer

    but i could rather say int pnvalue=7 .. so during the lifetime of the program.. you will have pnvalue set to 7 always right..then why declare it using pointers ?

  • There are three primary reasons to use pointers:

    1) When you allocate memory using new, that memory does not go out of scope when the function ends (although the pointer pointing to it will). This can be desirable in some cases.

    2) When working with arrays, you have to use a pointer in order to do dynamically sized arrays. You can not do something like this:

    int anArray[nSize];
    

    3) When working with large chunks of memory, it is better to allocate them on the heap (dynamically, using new) than the stack (via a normal variable).

  • Algernon

    #include
    #include

    void main()
    {
    clrscr();
    int *ptr;
    int n=20;
    ptr=new int[n];
    ptr[5]=7;
    ptr[6]=9;
    cout<<ptr[5]<<” “<<ptr[6]<<” \n”;
    delete[] ptr;
    cout<<ptr[5]<<” “<<ptr[6];
    getch();
    }

    cant seem to understand…even after i use the delete function the values of ptr[5] and ptr[6] are still displayed….

    • csvan

      I believe this is because delete[] only releases the memory referenced by ptr, it does not destroy the information already stored in them. That is why you can still view them, as ptr still stores the same memory address, and the data you defined before still resides in those very same addresses.

      However, you should ask somebody who knows this better!

  • steve

    I dont know if this is a recent change, but the lengths of arrays do not need to be constant like you said at the top.

    You can cin >> arraylength and then declare the array.

    • csvan

      Steve, this is a compiler question. For example, I believe GCC allows you to do that (declare arrays using a variable), however VS for example, as far as I know, allows no such thing.

      As far as the C++ standard is concerned, I am not sure what is technically correct, but beware that this difference exists!

      Keep coding. Use it for good :)

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

    thx.

  • me

    Hi

    Is this code right?

    
    int* ptr = new int[1];
    delete[] ptr;
    

    Thanks.

  • Anubhav Chattoraj

    Hi.
    Any way of dynamically initializing a two(or more)-dimensional array?
    It doesn’t let me do this….

    int *matrix1 = new int[row][col];
    

    (row and col being variables)

    Thanks…

  • Aakash Jain

    Hi Alex, kudos to your site.
    In the following code, I am trying to make a sample program with functions to accept/print a dynamically allocated matrix. The output isn’t working as expected. Please point out the errors.

    #include<iostream.h>
    using namespace std;
    
    void input(int **a, int x, int y)
    {
    	for (int i=0; i<x; i++)
    		for (int j=0; j<y; j++)
    			cin>>a[x][y];
    }
    
    void output(int **a, int x, int y)
    {
    	for (int i=0; i<x; i++)
    		for (int j=0; j<y; j++)
    			cout<<a[x][y];
    }
    
    int main()
    {
    	int x=0,y=0;
    	cin>>x>>y;
    	int **a=new int*[x];
    	for (int i=0; i<x; i++)
    		a[i]=new int[y];
    	input(a,x,y);
    	output(a,x,y);
    	return 0;
    }
    

    A similar program for a 1 dimensional array works.

  • Hi Alex,

    Great info! thanks! I have a question on:

    What is the correct way to de-allocate memory (delete) after creating many individual objects with new?

    say,

    
    for (int row = 0; row < rowCount; row++ )
    {
    	State* pStateItem = new State();
    	pStateItem->Name        = aState[row][0]->Name;
    	pStateItem->Description = aState[row][1]->Description;
    	StateVector->push_back(pStateItem);
    }
    DoSomething(StateVector);
    
  • [...] 6.9 Dynamic memory allocation with new and delete [...]

  • george

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

    int *p = (int*)(0x00345D45);
    

    and then I assign a value:

    *p = 8;
    

    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.

  • drow

    How would I dynamically allocate one part of a two dimensional array. i.e.

     anarray[variable][80] 

    because this doesn’t work:

     int foundobjects=0;
    char (*founditems) = new char[foundobjects][80]; 
  • Sijo
    int *pnPtr1 = new int;
    int *pnPtr2 = pnPtr1;
    delete pnPtr1;
    pnPtr1 = 0;
    
    if (pnPtr2)
        *pnPtr2 = 5;
    

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

  • ravi

    Plz sir, check why this code is working????

    #include
    using namespace std;
    int main()
    {
    cout <> nVars;
    int a[nVars]; // wrong! The size of the array must be a constant
    for(int i=0;i>a[i];
    }
    for(int i=0;i<nVars;i++){
    cout<<a[i]<<"\n";
    }
    }
    I compiled this code on g++ compiler, its working,plz sir,explain.

  • fmunshi

    Hi Alex,

    In your explanation of Null Pointers (Part II) it seems you have a typo in the third code snippet:

    1 int *pnValue = new int;
    2 delete pnValue; // pnValue not set to 0
    3
    4 if (pnValue)
    5 *pnValue = 5; // will cause a crash

    You should add the following between line 1 and line 2:
    *pnValue = 7;

    Since in the fourth code snippet where you correct the Null pointer error you have “*pnValue = 7;” already inserted, it might confuse some people into thinking that assigning *pnValue to 7 has something to do with fixing the Null pointer.

    Thanks for the excellent tutorials!!!
    Fardan

  • SWEngineer

    Simple well explained tutorial.

    Thanks.

  • #include “FileUtils.h” // Pulls all includes, namespace std and file stream functions

    int main(){
    int rounds = 0; // Rounds initializer valueint
    hole = 0; // Hole initializer valueint
    players = 4; // Default maximum number of players per game
    string *Player = new string [players]; // String array to hold Player names
    int *Scores = new int [players][22]; // 18 Holes+Front and Back 9+Handicap+Total

    cout << "Welcome to the Golf Score Card program! " << endl; // Welcome message
    cout <> rounds; cout << endl; // User inputs number of games they wish to enter information for

    for(int i = 0; i < rounds; i++){ // Golf gameplay loop limits number of rounds to number specified
    cout <> players; cout << endl; // User inputs number of players

    if(players = 1){ // If statement checks for single player game
    cout <> Player[0]; cout << endl; // User enters their name}

    else{cout <> Player[0]; cout << endl; // User enters name of first player in group into Player string array

    for(int j = 1; j < players; j++){ // For loop to gather names of any remaining players
    cout <> Player[j]; cout << endl; // User enters names of remaining players of group into Player string array
    }}

    fflush(stdout); // Clears screen of all previous outputs
    cout << "Welcome "; // Custom welcome message to all players to the game

    for(int k = 0; k < players; k++){ // for loop to list each player name in a grammatically correct style
    cout << Player[k] << ", ";}
    cout << "to the game! " << endl; // last section of custom welcome message

    for(int r = 0; r < 9; r++){

    }

    // Calculate First 9 for all players, output to array[9]

    for(int r = 10; r < 19; r++){

    }

    // Calculate Back 9 for all players, output to array[19]
    // Calculate Handicap for all players, output to array[20]
    // Calculate Total score for all players, output to array[21]

    /*bogey +1
    doublebogey +2
    birdie -1
    eagle -2
    front 9 / back 9
    handicap = strokes – 72 (total among 18 holes)*/
    }

    const string ScoreCard = "ScoreCard.txt"; // Declares text file assigned to string ScoreCard

    //This method can be found in FileUtils.cpp
    outputToFile(ScoreCard, "This is a test");
    appendToFile(ScoreCard, "Test line 2");
    getInputFromFile(ScoreCard); return 0;}

    This line: int *Scores = new int [players][22]; // 18 Holes+Front and Back 9+Handicap+Total

    is giving me an error saying i can’t initialize an entity of type int with a value of type int. Any suggestions on how to correct this? I need that array to be [number of players down][scores going across]

    It all has to be dynamic to accomodate differing number of players after each round.

    Thanks

  • computer_brad

    i think I’m missing the general idea. i’m reading the top of the page where it mentions using an array to hold a name, without using too much or too little memory. This snippit doesn’t compile. Am I going in the wrong direction with this topic?

    #include

    int main()
    {
    using namespace std;
    char *szFirstName = new char;
    char *szLastName = new char;
    cout << "first name" <> *szFirstName;
    cout << "last name" <> *szLastName;
    cout << sizeof(*szFirstName) << endl;
    cout << sizeof(*szLastName) << endl;
    return 0;
    }

  • capitanui

    Hello,

    Does someone know if i can assign dynamically multidimensional arrays?

    something like :

    int xSize;
    int ySize;
    char *pcArray = new char[xSize][ySize];

    • Mezo Soft

      Yes capitanui … you can assign dynamically multidimensional array , but you must determine the number of the column numbers (ySize) in your example

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

  • richardholy

    Hello,

    example from this tutorial does not cause crash. I have MSV C++ 2010 Express:

    #include “stdafx.h”
    #include

    int main()
    {
    using namespace std;

    int *pnValue = new int;
    delete pnValue; // pnValue not set to 0

    if (pnValue)
    *pnValue = 5; // will cause a crash

    cout << *pnValue;
    }

    It prints "5".

  • JohnDepth

    Hmmmm… I usually use deleaker for search memory or GDI 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;
    }

You must be logged in to post a comment.