Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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 ''.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...