c++ - Seg Fault when creating dynamic array of strings -
my friend writing text-based game , asked me @ code crashing. debugged , getting seg fault when creating dynamic array. i'm not sure why, recommended avoid pointers altogether , use vector solve problem i'm curious going wrong here. here's 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; }
you calling tellg
:
listlength = filename.tellg();
without having read anything, depending on whether file opening or not return 0
or -1
, have called:
namepartlist = new string[listlength]
with undesirable value. pretty sure returning -1
since allocating 0 sized should ok.
this applies later on code well, going std::vector
makes more sense.
Comments
Post a Comment