<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>
<channel>
	<title>Comments on: 6.9 &#8212; Dynamic memory allocation with new and delete</title>
	<atom:link href="http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/</link>
	<description></description>
	<pubDate>Wed, 20 Aug 2008 08:25:25 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
		<item>
		<title>By: Learn C++ - &#187; 6.8 &#8212; Pointers, arrays, and pointer arithmetic</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-13479</link>
		<dc:creator>Learn C++ - &#187; 6.8 &#8212; Pointers, arrays, and pointer arithmetic</dc:creator>
		<pubDate>Tue, 29 Apr 2008 04:54:02 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-13479</guid>
		<description>[...] 2007      Prev/Next Posts   &#171; 6.7 &#8212; Introduction to pointers &#124; Home &#124; 6.9 &#8212; Dynamic memory allocation with new and delete &#187;     Wednesday, July 11th, 2007 at 6:20 [...]</description>
		<content:encoded><![CDATA[<p>[...] 2007      Prev/Next Posts   &laquo; 6.7 &#8212; Introduction to pointers | Home | 6.9 &#8212; Dynamic memory allocation with new and delete &raquo;     Wednesday, July 11th, 2007 at 6:20 [...]</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Petter</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-9071</link>
		<dc:creator>Petter</dc:creator>
		<pubDate>Fri, 07 Mar 2008 16:06:24 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-9071</guid>
		<description>Thanks!
It now works as it should! Thanks for clearing it up :)

These tutorials are great BTW!</description>
		<content:encoded><![CDATA[<p>Thanks!<br />
It now works as it should! Thanks for clearing it up :)</p>
<p>These tutorials are great BTW!</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Alex</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-9068</link>
		<dc:creator>Alex</dc:creator>
		<pubDate>Fri, 07 Mar 2008 15:23:24 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-9068</guid>
		<description>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:

&lt;pre&gt;
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
}
&lt;/pre&gt;

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.</description>
		<content:encoded><![CDATA[<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&#8217;t.  It&#8217;ll simply set vertices to point to those elements.</p>
<p>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.</p>
<p>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.</p>
<p>Second, to see why Add() crashes, simply step through your code when vertices is non-null (which it is when you&#8217;ve called the above constructor):</p>
<p>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.</p>
<p>You basically have the right idea, you&#8217;ve just assumed that assigning one pointer to another will copy the elements, and it won&#8217;t.  It&#8217;ll just make them point to the same thing.</p>
<p>Your add function should look like this:</p>
<pre>
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&#8217;t need this
   vertices = tmp;
   delete[] tmp; // or this

// increment numVerts here
}
</pre>
<p>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.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Petter</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-9048</link>
		<dc:creator>Petter</dc:creator>
		<pubDate>Fri, 07 Mar 2008 09:58:54 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-9048</guid>
		<description>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:

&lt;pre&gt;class Polygon {
    
    private:
        Vertex* vertices;
        int numVerts;
    public:
        
        //Constructors
        Polygon(Vertex vert[], int numVerts){
            vertices = vert;
            this-&#62;numVerts = numVerts;
        }
        
        Polygon() {
            vertices = 0;
            numVerts = 0;
        }
...
&lt;/pre&gt;

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:

&lt;pre&gt;
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;
            
}&lt;/pre&gt;

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</description>
		<content:encoded><![CDATA[<p>I&#8217;m working on an assignment for a course I&#8217;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:</p>
<pre>class Polygon {

    private:
        Vertex* vertices;
        int numVerts;
    public:

        //Constructors
        Polygon(Vertex vert[], int numVerts){
            vertices = vert;
            this-&gt;numVerts = numVerts;
        }

        Polygon() {
            vertices = 0;
            numVerts = 0;
        }
&#8230;
</pre>
<p>The parameterless constructor thus creates an &#8220;empty&#8221; Polygon. There is however a function add() with which you can add a Vertex to the Polygon. I have written it like this:</p>
<pre>
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;

}</pre>
<p>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&#8217;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?</p>
<p>Thanks!</p>
<p>/P</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Abdul</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-5995</link>
		<dc:creator>Abdul</dc:creator>
		<pubDate>Mon, 14 Jan 2008 08:53:07 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-5995</guid>
		<description>In making class Biginteger how we can use dynamic memory allocation</description>
		<content:encoded><![CDATA[<p>In making class Biginteger how we can use dynamic memory allocation</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Alex</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-5930</link>
		<dc:creator>Alex</dc:creator>
		<pubDate>Sat, 12 Jan 2008 19:19:48 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-5930</guid>
		<description>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 80x86 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.</description>
		<content:encoded><![CDATA[<p>1) Each &#8220;chunk&#8221; of memory has to have a unique address, otherwise there&#8217;d be no way to address that chunk of memory individually.  On the 80&#215;86 architecture, the size of that &#8220;chunk&#8221; is a byte, which means we can address individual bytes.  The address of 0 is used to mean &#8220;not pointing to anything&#8221;.</p>
<p>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?)</p>
<p>3) Thanks, I&#8217;ll get that fixed.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Renu</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-5918</link>
		<dc:creator>Renu</dc:creator>
		<pubDate>Sat, 12 Jan 2008 15:27:13 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-5918</guid>
		<description>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</description>
		<content:encoded><![CDATA[<p>1   &#8220;Null pointers (pointers set to address 0) &#8230;.&#8221;<br />
Cant 0 be address of any memory location?</p>
<p>2   int nSize = 12; int *pnArray = new int[nSize]; [4] = 7; delete[] pnArray; </p>
<p>    Why is subscript not required in delete?<br />
    like<br />
    delete[nSize] pnArray; </p>
<p>3   Typo-<br />
    This allows &#8220;us to us to&#8221; do things like conditionally allocate memory:</p>
<p>Thanks,<br />
Renu</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Bob Dole</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-3054</link>
		<dc:creator>Bob Dole</dc:creator>
		<pubDate>Mon, 19 Nov 2007 23:05:58 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-3054</guid>
		<description>Amazon's affiliate content is not loading properly and causing your website to hang. Please fix the div load order so I don't have to wait 10 minutes for Amazon to time out and the remainder of the page to display. Otherwise, incredibly helpful content, thank you!

[ The Amazon stuff has been temporarily disabled. -Alex ]</description>
		<content:encoded><![CDATA[<p>Amazon&#8217;s affiliate content is not loading properly and causing your website to hang. Please fix the div load order so I don&#8217;t have to wait 10 minutes for Amazon to time out and the remainder of the page to display. Otherwise, incredibly helpful content, thank you!</p>
<p>[ The Amazon stuff has been temporarily disabled. -Alex ]</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: sergk</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-107</link>
		<dc:creator>sergk</dc:creator>
		<pubDate>Mon, 16 Jul 2007 09:44:57 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-107</guid>
		<description>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/)</description>
		<content:encoded><![CDATA[<p>If by &#8220;some of which C++ support and some of which it doesn&#8217;t&#8221; 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/)</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Alex</title>
		<link>http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-104</link>
		<dc:creator>Alex</dc:creator>
		<pubDate>Sat, 14 Jul 2007 19:36:03 +0000</pubDate>
		<guid isPermaLink="false">http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/#comment-104</guid>
		<description>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:

&lt;pre&gt;
int *pnPtr1 = new int;
int *pnPtr2 = pnPtr1;
&lt;/pre&gt;

Now both pointers point to the dynamically allocated memory.  However, if you do this:

&lt;pre&gt;
delete pnPtr1;
pnPtr1 = 0;
&lt;/pre&gt;

pnPtr2 is left pointing to deallocated memory!  And thus a call like this:

&lt;pre&gt;
if (pnPtr2)
    *pnPtr2 = 5;
&lt;/pre&gt;

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.</description>
		<content:encoded><![CDATA[<p>That is a great point, Sergk.  Thanks for bringing it up.</p>
<p>What Sergk is talking about is the fact that you can have multiple pointers pointing to the same bit of dynamically allocated memory.  Let&#8217;s say you do something like this:</p>
<pre>
int *pnPtr1 = new int;
int *pnPtr2 = pnPtr1;
</pre>
<p>Now both pointers point to the dynamically allocated memory.  However, if you do this:</p>
<pre>
delete pnPtr1;
pnPtr1 = 0;
</pre>
<p>pnPtr2 is left pointing to deallocated memory!  And thus a call like this:</p>
<pre>
if (pnPtr2)
    *pnPtr2 = 5;
</pre>
<p>will cause your program to crash, even though it seems like it should be okay.</p>
<p>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&#8217;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&#8217;t always reasonable.</p>
]]></content:encoded>
	</item>
</channel>
</rss>
