I have a problem with simple reading from the file that shares file pointer between a few objects (It works for me with just simple istream, but not when I am using shared pointer of istream pointers).
I am trying to read the whole file to the buffer (file itself is a few lines long.
The code compiles, but throws segmentation fault.
The class that uses shared_ptr:
RecordsSplitter::RecordsSplitter(char *filename):iStream( new ifstream(filename, ifstream::in|ifstream::binary))
{
}
string RecordsSplitter::buildRecord() {
char *buffer;
int buffer_length;
iStream->seekg (0, ios::end)_
buffer_length = iStream->tellg();
cout << buffer_length;
iStream->seekg(0, ios::beg);
iStream->read(buffer,buffer_length);
iStream->close();
cout << buffer;
return 0;
}
int main(int argc, char* argv[]) {
RecordsSplitter *splitter;
splitter = new RecordsSplitter(argv[2]);
int return_num = splitter->buildRecord();
return 0;
}
You declare your buffer but you don't initialise it anywhere. You need this in your buildRecord
function or a use of malloc if you so desire.
buffer = new char[buffer_length];
Your seg fault is caused by this uninitialised pointer
Don't forget to clean up!
delete[] buffer;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.