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:
I think Nathaniel answered your bigger question, but I just have to
point this out:
> #include <iostream>
> using namespace std;
>
> void GrowArray(char **, int, int);
>
> int main()
> {
> char ** words;
> char * word;
> int size = 2;
>
> words = new char * [size];
>
> word = new char[5];
> word = "Foo";
You just leaked some memory here. The 'new char[5]' allocates memory
from the heap and returns a pointer to that memory which is then
stored in word. The next line overwrites what's in word with the
const char * "Foo". The original pointer to the allocated heap memory
is lost. The solution here would be to simply not do the new. The
compiler will allocate the memory for "Foo" on the stack for you.
You did this twice actually. Sure, this is in your brief main()
function, so the leak won't last long, but you really shouldn't allow
yourself to do this ever. Have you heard of the STL and vectors?
They were invented for this kind of stuff.
Bryan
--------------------
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