I was working on this function read. The main I used has no problem in file I/O, it connects fine, closes, the files are okay too. However, I am getting a segmentation fault by the end of the reading. I have tried printing out for testing, and the error is reading the last line. It finishes reading the last line for string a, and then x, and then in.good() becomes false too. I have tried resetting in.clear(), also, setting the string a=""; if in.good becomes false. Nothing is working.
read(istream& in){
string a;
int x;
in>>a;
while( in.good() ){
in>>x;
char *ch;
strcpy( ch, a.c_str() );
Word cwd(ch);
anObject.add(cwd,x);
}
}
You see a segfault because you’re not allocating space for
ch, and then you’re attempting to copy a string over it.chis an uninitialized memory address that doesn’t belong to you.You’ll need to allocate space for the string:
But why is it that you need a
char *here? Note that you can always pass aroundaand usea.c_str()if you must have a C string. I’m not sure whatWordis, or if it needs it’s own copy of a string, but can you use:Word cwd(a.c_str())?