* Nathaniel Price [Sat, 15 Sep 2007 at 21:54 -0600]
<quote>
> On 9/15/07, Nicholas Blatter <[EMAIL PROTECTED]> wrote:
> > I remember seeing some discussion before about a problem in C++ so I
> > thought I might send one of my own.  It has been a looong time since
> > I've done much at all in C++ and I'm having problems with some
> > (seemingly simple) memory management.
> >
> > I'm trying to expand an array of cstrings with a function call.  I'm
> > sure there's something simple I'm not remembering... here's the whole
> > thing:
> [snip]
> > void GrowArray(char ** array, int oldSize, int newSize)
> > {
> >    char ** temp = new char * [newSize];
> >
> >    for (int i = 0; i < oldSize; i++)
> >       temp[i] = array[i];
> >
> >    delete [] array;
> >    array = temp;
> > }
> >
> 
> The problem is that the char ** pointer that points to the words array
> is being passed to GrowArray() by value and not by reference. Thus the
> pointer to the new array you create inside the function is lost as
> soon as you return out of it, since the variable array is only a copy
> of the pointer to words and not the original pointer itself. Change
> the function declaration to this (if I recall the syntax for passing a
> pointer by reference) and that should fix it:

Correct me if I'm wrong, but char ** temp still lives on the stack, even
if you assign it to array once changing array to be passed by reference,
it's still going to point to an obsolete stack space, from which Bad
Things TM will happen. It just so happens in this case that obsolete
stack space is never reused because that was the last function call, so
it works... but it's still not right.

Von Fugal

Attachment: signature.asc
Description: Digital signature

--------------------
BYU Unix Users Group 
http://uug.byu.edu/ 

The opinions expressed in this message are the responsibility of their
author.  They are not endorsed by BYU, the BYU CS Department or BYU-UUG. 
___________________________________________________________________
List Info: http://uug.byu.edu/mailman/listinfo/uug-list

Reply via email to