user768417
user768417

Reputation:

Seg Fault when creating dynamic array of strings

My friend is writing a text-based game and asked me to look at this code that was crashing. I debugged it and it was getting a seg fault when creating a dynamic array. I'm not sure exactly why, I recommended he just avoid pointers altogether and use a vector so hopefully that will solve his problem but I'm curious as to what exactly is going wrong here. Here's his code:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

class nation
{
    public:
    void init();
    string genName();
    string getName();

    private:
    string myName;
    int* myBorderPoints;
};

string nation::getName()
{
    return myName;
}

string nation::genName()
{
    int listLength = 0, listPos = 0, listRand = 0;
    string nameToGen = "";
    string* namePartList;
    ifstream fileName;
    fileName.open("NamePart1.txt");
    listLength = fileName.tellg();
    namePartList = new string[listLength]; // Seg fault here
    while (fileName.good())
    {
        while (!fileName.eof())
        {
            getline(fileName,namePartList[listPos]);
            listPos += 1;
        }
    }
    listRand = rand() % listLength;
    nameToGen += namePartList[listRand];
    fileName.close();
    listLength = 0;
    listPos = 0;
    listRand = 0;
    nameToGen = "";
    fileName.open("NamePart2.txt");
    listLength = fileName.tellg();
    namePartList = new string[listLength];
    while (fileName.good())
    {
        while (!fileName.eof())
        {
            getline(fileName,namePartList[listPos]);
            listPos += 1;
        }
    }
    listRand = rand() % listLength;
    nameToGen += namePartList[listRand];
    fileName.close();
    return nameToGen;
}

void nation::init()
{
    srand(time(NULL));
    myName = genName();
}

int main()
{
    nation testNation;
    testNation.init();
    cout << testNation.getName();
    return 0;
}

Upvotes: 0

Views: 229

Answers (1)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158469

You are calling tellg:

listLength = fileName.tellg();

without having read anything, which depending on whether the file was opening successfully or not will return 0 or -1 and so you will have this called:

namePartList = new string[listLength]

with a probably a undesirable value. I am pretty sure it is returning -1 since allocating a zero sized should be ok.

This also applies later on the code as well, going with std::vector probably makes more sense.

Upvotes: 1

Related Questions