c++ - Segmentation fault, and passing in pointers -
when running code below, getting segmentation fault (core dumped).
i've been told seg faults due bad pointers of time. now, relatively new language , being said i'm sure doing wrong here can't spot due inexperience , current level of proficiency.
the code below creating vector of peekdeque<stringwrap> objects in main method. passes pointer vector function testnewword. function creates new peekdeque<stringwrap> object , pushes of vector. well, that's i'm trying anyways!
#include <iostream> #include <algorithm> #include <string> #include <vector> #include <fstream> #include <sstream> using namespace std; void testnewword(string word, vector<peekdeque<stringwrap> >* chains) { peekdeque<stringwrap>* newpd = new peekdeque<stringwrap>(100); newpd->pushfront(stringwrap(word)); chains->push_back(*newpd); } int main(int argc, char* argv[]){ vector<peekdeque<stringwrap> >* chains = new vector<peekdeque<stringwrap> >(); string word; string infilename = argv[1]; ifstream* infilep = new ifstream(infilename.c_str(), ios_base::in); while ((*infilep) >> word) { testnewword(word, chains); } infilep->close(); } what doing wrong here? perhaps delete being called on null pointer? go easy on me.
none of places use pointer here need (nor should be) pointers. instead should regular object, , passed via references.
try replacing:
vector<peekdeque<stringwrap> >* chains = new vector<peekdeque<stringwrap> >(); with simply:
vector<peekdeque<stringwrap> > chains; and
void testnewword(string word, vector<peekdeque<stringwrap> >* chains) { peekdeque<stringwrap>* newpd = new peekdeque<stringwrap>(100); with:
void testnewword(const string& word, vector<peekdeque<stringwrap> >& chains) { peekdeque<stringwrap> newpd(100); read more on when should use references vs. pointers. in general c++, use pointers if absolutely cannot use reference. you'll have change -> . because references act actual object, not pointer it.
Comments
Post a Comment