Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

Segmentation fault when writing char array to file in C

When I run the following code, I get a "Segmentation fault" at fprintf(outfile, "%s", inputline[j]);.

I am unable to understand what is the cause for the error. I am relatively new to C, can someone please help me resolve the error?

void test(char *inputline) {
    FILE *outfile = fopen("results.txt", "w");   
    if (!outfile) {
        perror("Error while opening file: ");
    } else {
        for (int j = 0; j < 20; ++j) { // I only want to be write the first 20 characters to the file that is why I have the iteration till only 20 and added [j], is that correct way to do it?
            fprintf(outfile, "%s", inputline[j]);
        }
    }
}

//Function call
    ...
    char inputline[40] = "hello world 123 456"; //passed to the function above
    test(inputline);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Format specifier %s in

fprintf(outfile, "%s", inputline[j]);

expects a char * variable, but you are actually passing a char (j th element of inputline array).

The reason why a segmentation fault occurs is that fprintf tries to "access" the memory location poited by the passed character. And since it will be very likely an invalid address the OS will complain about the attempt to access the memory outside the space assigned to your application.

You can either print to file char by char, keeping the for-loop and using %c format

 for(int j=0; j<20; ++j)
 {
     fprintf(outfile, "%c", inputline[j]);
 }

or print the whole string keeping the %s format, passing the whole array and getting rid of the for-loop:

fprintf(outfile, "%s", inputline);

Note: in the first case 20 characters will be written, anyway. In the second case "length+1" characters because of the string terminator ''.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...