bad_alloc exception after call to function

void display(FlexArray f, ostream& out, int lower, int upper)
// POST: display list of id and name pairs to desired output stream from lower to upper
{
string buffer4;
for (int i = 0; i < f.count(); i++)
{
buffer4 = f.getValue(i); //Using the combined values in the list, display names with asterisks
buffer4.insert(4, "*");
buffer4.append("*");
out << "\n" << buffer4;
}

}

The error comes after I call this -> display(combined, cout, 0, 100);
and then I try to do combined.getValue(12); It reads 'Error reading characters of string'

This is the getValue member function:
string FlexArray::getValue(int index) const
// PRE: lower <= index <= upper
// POST: return value at index
{
if ((lower <= index) && (upper >= index) && (index < size))
return list[index];
}
I think I have found out my problem. My copy constructor is this:
FlexArray::FlexArray(const FlexArray& other)
// POST: object is copy of other
{

capacity = other.capacity;
size = other.size;
lower = other.lower;
upper = other.upper;
if (other.list) {
list = new string[capacity];
list = other.list;
}
}

The problem I think is when display() ends, the FlexArray parameter, f, gets destroyed and it shares the address of the original object and hence all the data is lost. I want to know how to perform this copy of the object but keeping both objects with distinct addresses.
std::copy(other.list, other.list + other.size, list) will copy the strings from the old array to the new one, while preserving the new pointer.
Note that the copy constructor is not initializing this->list if !other.list, leaving the pointer invalid.
Topic archived. No new replies allowed.