Getting a segfault. Can't find it.
Narrowed it to this function via gdb. it segfaults when the 2nd for loop starts / is supposed to start.
Code:
void file_reverse_output(FILE * file, FILE * newfile, const char type) |
(Let's hope you call `rewind` after `file_num_lines`.)
You have an off-by-one error. Also you didn't check the return value of `fgets`. Code:
void file_reverse_output(FILE * file, FILE * newfile, const char type) |
Guess you are working with a file that misses the terminating NewLine character. That should be solved otherwise, e.g.
Code:
static int file_num_lines(FILE *file) { Code:
static int file_num_lines(FILE *file) { Code:
void file_reverse_output(FILE * file, FILE * newfile, const char type) |
int lines = file_num_lines(file);
char buf[lines + 1][256]; If you're going to dynamically size buffers then use malloc(). VLAs were added in C99, but they were downgraded to an "optional feature" in C11. Unless you have a good reason not to (such as a recursive function where stack usage might matter it's often just easier to allocate a large enough buffer to hold the largest entry rather than try and do anything clever. |
Ok thank you. Will make some adjustments and report back. Thank you again.
|
the best tool to catch that kind of errors is valgrind. (ok, probably not the best, but definitely a very good tool).
|
Got it working. I followed the above suggestions. This now does both file or stdout depending on the flag used. I can see that I need to spend more time with validating functions.
Code:
void file_reverse_output(FILE * file, FILE * newfile, const char type) |
Also you can use `stdout` as `newfile` and drop parameter `type`.
|
I suggest you learning Valgrind and GDB. With these two tools your debugging process will be easier.
|
All times are GMT -5. The time now is 12:36 PM. |