C语言作业遇Segmentation fault求助:文件字符右移写入异常
Hey there! Segmentation faults are super common when you're getting started with C—they usually boil down to accessing memory you don't own, but let's walk through the most likely culprits in your program and how to fix them.
Common Causes & Fixes
Forgot to check if files opened successfully
If you callfopen()but don't verify the returned pointer isn'tNULL, you'll crash when you try to read/write to a non-existent file handle. Always add a check right after opening:FILE *in_file = fopen("input.txt", "r"); if (in_file == NULL) { perror("Failed to open input file"); return 1; }Do the same for your output file—don't skip this step!
Uninitialized or misused pointers
If you declared achar *without allocating memory (likechar *buf;instead ofchar buf[256];orchar *buf = malloc(256);), writing to it will cause a segfault. If you usedmalloc, make sure you checked that it didn't returnNULLtoo. Also, watch out for array out-of-bounds errors—don't write more characters than your buffer can hold.Not handling EOF correctly
When usingfgetc(), it returnsEOFwhen it reaches the end of the file. If your loop doesn't check forEOFand keeps trying to read, you'll end up accessing invalid memory. Your loop should look something like this:int c; // Use int, not char—EOF is an int value outside the char range while ((c = fgetc(in_file)) != EOF) { // Process and write the character }Forgetting to close files (less likely, but still risky)
While not always the direct cause of a segfault, leaving files open can lead to resource leaks and unexpected behavior. Make sure you callfclose()on every file you opened, even if an error occurs.
Example Working Code
Here's a simplified version of what your program should look like to avoid these issues:
#include <stdio.h> #include <stdlib.h> int main() { int shift_amount = 2; // Adjust this to your required shift value FILE *input = fopen("input.txt", "r"); if (input == NULL) { perror("Failed to open input file"); return EXIT_FAILURE; } FILE *output = fopen("output.txt", "w"); if (output == NULL) { perror("Failed to open output file"); fclose(input); // Clean up before exiting return EXIT_FAILURE; } int current_char; while ((current_char = fgetc(input)) != EOF) { // Perform logical right shift—adjust logic based on your requirements char shifted_char = (unsigned char)current_char >> shift_amount; fputc(shifted_char, output); } // Clean up fclose(input); fclose(output); return EXIT_SUCCESS; }
Compare this to your code—look for places where you might have skipped checks, used uninitialized memory, or mishandled file reads. If you're still stuck, sharing a snippet of your code would help narrow it down even more!
内容的提问来源于stack exchange,提问作者Karker Carnesir

