0

I am working on an assignment to create a container class for a dynamic array of strings. I know this would be far better done with a std::vector, but that is not the 'pointer' of the assignment.

From what I can tell, my program hangs during the delete [] lineArray step below.

MyBag::MyBag()
{
    nLines = 0;
    lineArray = new std::string[0] ();
}
void MyBag::ResizeArray(int newLength)
{
    std::string *newArray = new std::string[newLength];
    //create new array with new length
    for (int nIndex=0; nIndex < nLines; nIndex++)
    {
        newArray[nIndex] = lineArray[nIndex];
        //copy the old array into the new array
    }
    delete[] lineArray; //delete the old array
    lineArray = newArray; //point the old array to the new array
    nLines = newLength; //set new array size
}
void MyBag::add(std::string line)
{
    ResizeArray(nLines+1); //add one to the array size
    lineArray[nLines] = line; //add the new line to the now extended array
    nLines++;
}

The entire program is here http://pastebin.com/KnL4XmAw

Ian Fiddes
  • 2,821
  • 5
  • 29
  • 49
  • At what point does it crash? On the first `add()` call? We don't have the input file, so even with the full code we can't tell when the crash occurs. – Chad May 13 '13 at 18:11
  • 1
    A couple of things to consider: 1) what happens if `newLength` is less than the string's current length? 2) Follow the [rule of three](http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29). – juanchopanza May 13 '13 at 18:13
  • 1
    Just a suggestion use `std::vector` for `lineArray` – stardust May 13 '13 at 18:18

2 Answers2

3
ResizeArray(nLines+1); //add one to the array size
lineArray[nLines] = line; //add the new line to the now extended array
nLines++;

The call to ResizeArray has already adjusted the value of nLines. The increment in the last line is wrong, as is the use of lineArray[nLines] in the next to last line.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
1

A problem is in add:

ResizeArray(nLines+1); //add one to the array size - INCREMENTS nLines
lineArray[nLines] = line; //add the new line AFTER THE END OF the now extended array
nLines++;                 //add another one to the array size - WRONG

This should be:

ResizeArray(nLines+1); //add one to the array size
lineArray[nLines-1] = line; //add the new line to the now extended array

Also, if you're writing a class to manage dynamic resources like this, make sure you consider the Rule of Three. Yours will go horribly wrong if you ever copy it.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644