When I try to run my program, I get the wrong number of lines printed.
LINES: 0
This is the output although I have five lines in my .txt fi
I don't see anything immediately obvious as to what would cause a segmentation fault. My only suspicion is that your code expects to get a filename as a parameter when you run it, but if you don't pass it, it will attempt to reference one, anyway.
Accessing argv[1]
when it doesn't exist would cause a segmentation fault. It's generally good practice to check the number of arguments before trying to reference them. You can do this by using the following function prototype for main()
, and checking that argc
is greater than 1 (simply, it will indicate the number entries in argv).
int main(int argc, char** argv)
The best way to figure out what causes a segfault in general is to use a debugger. If you're in Visual Studio, put a breakpoint at the top of your main function and then choose Run with debugging instead of "Run without debugging" when you start the program. It will stop execution at the top, and let you step line-by-line until you see a problem.
If you're in Linux, you can just grab the core file (it will have "core" in the name) and load that with gdb
(GNU Debugger). It can give you a stack dump which will point you straight to the line that caused the segmentation fault to occur.
EDIT: I see you changed your question and code. So this answer probably isn't useful anymore, but I'll leave it as it's good advice anyway, and see if I can address the modified question, shortly).