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

Popular posts from this blog

php - SPIP: From Tag directly to an article -

jquery - isAjaxRequest always return false -

ruby on rails - In a controller spec, how to find a specific tag in the generated view? -