Passing Streams Into functions

Apr 11, 2018 at 3:40pm
I was trying to make a function that parses an object from a stream
and append it to a list it always ends up creating a segmentation fault.

1
2
3
4
5
6
7
8
9
10
  //The usual
void loadItem(ifstream& ifs){
char buffer[256];
ifs.getline(buffer, 256);
//parsing code goes here
students.pop_front(student);
}
int main(){
ifstream ifs("File.txt");
Item* item = loadItem(ifs);
Last edited on Apr 14, 2018 at 5:55am
Apr 11, 2018 at 4:24pm
Your loadItem function claims to return an Item* but actually it doesn't return anything at all.
Apr 14, 2018 at 5:55am
sorry for the misinformation the return type was void(It wouldn't have compiled otherwise). It just causes a segmentation fault at run time.
Last edited on Apr 14, 2018 at 5:57am
Apr 14, 2018 at 8:24am
It's very hard to guess what the problem is without seeing real code.
Apr 14, 2018 at 9:24am
If the return type of loadItem is void, line 10 makes no sense and item will be a bad pointer that will cause a segfault when you try to use it. If your compiler even lets you get this far.

We're not psychic. You've said "my code segfaults, but 'm not going to show you my code; now please guess what the problem is". That's not very helpful.

Apr 14, 2018 at 1:43pm
How many items are in the students collection before line 6 runs? If it's zero, that could cause a crash.

Just as a design choice, I would change the parameter of loadItem from ifstream& to istream& That makes the function more general.

If this doesn't help then please post a full program that we can compile. Without compilable code, it's very hard to diagnose the problem.
Topic archived. No new replies allowed.