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:
#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";
words[0] = word;
word = new char[5];
word = "Bar";
words[1] = word;
cout << "before 0: " << words[0] << endl;
cout << "before 1: " << words[1] << endl;
GrowArray(words, size, size * 2);
size *= 2;
// program breaks right here
cout << "after 0: " << words[0] << endl;
cout << "after 1: " << words[1] << endl;
return 0;
}
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 program has problems as soon as you try and access words[0] the
second time. After some playing around I'm guessing it has something
to do with the temp array and the function return, but I thought that
the point of using the new operator was to avoid that.
Sorry if this is completely stupid, but I really do appreciate any help :)
Thanks,
Nick
--------------------
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