I have a text file which contains only lines with a message like:
Hello there
howdy
Now I got this function that reads these lines and returns an array containing them.
string* printlines(string filename)
{
string line;
int sum = 2;
int i =0;
string *quotes;
ifstream infile(filename.c_str());
quotes= new string[2];
if (infile.is_open())
{
while (infile.good())
{
getline (infile,line);
quotes[i] = line; // <--- here's the problem
i++;
}
}
infile.close();
return quotes;
}
gdb reports that the line in bold has the problem but I don’t see it.
The loop structure is incorrect and will result in going beyond the end of the array. Even though there are only two lines in the file, no check is immediately after the
getline()to determine if was successful. The first two lines will be read but eof will not yet be set resulting in a thirdgetline()call, going beyond the end of the array.Change to:
Having said that, considering using a
std::vector<std::string>instead of an array:The
std::vectorwill dynamically grow to store all read lines. New lines can be added to the text file without any requirement for a code change.