Hick
Hick

Reputation: 36374

Why is this code causing a segmentation fault?

#include<stdio.h>


void main()
{
FILE  *fp,*fp1;
char c;
fp=fopen("test.txt","r");
fp1=fopen("test1.txt","w");
c=getc(fp);
while(c!=EOF)
{
    if (c=="")
    {
        c=getc(fp);
        continue;
    }
    else 
        fprintf(fp1,"%s",c);
    c=getc(fp);
}
fclose(fp);
fclose(fp1);

}

Upvotes: 0

Views: 2056

Answers (5)

CB Bailey
CB Bailey

Reputation: 791361

There are a number of things wrong with the code that might cause problems.

fp and fp1 should be checked against NULL after being assigned the result of fopen to check for file open failures.

The type of c should be int so that you can properly distinguish EOF from a valid character read correctly.

c == "" attempts to compare character value with the address of a literal zero-length string.

fprintf(fp1,"%s",c) interprets that character value c as the address of a constant string and attempts to follow this address to print a string. This is the most likely error to cause a segmentation fault.


Less important style issues.

The return value of main should be an int. It's portably correct even if many implementations do allow void main(void).

As the body of your if clause matches what would happen if the loop ran to the end and is followed by a continue, it would be probably be clearer to remove this clause and apply an if statement with the opposite of what you think c=="" should become, to what is currently the else statement.

Upvotes: 6

sud03r
sud03r

Reputation: 19749

The code gives segmentation fault due to illegal memory access, fprintf looks for null character to terminate and in this process accesses invalid memory location.
Also file pointers must be checked for null and code should exit gracefully if any of them is null otherwise it will also cause a segfault.

Upvotes: 0

Nelson
Nelson

Reputation: 29706

Your problem is the fprintf("%s") of the variable c. c is not a string, it's a single character. Replace that line with

fprintf(fp1,"%c",c);

And it will work. There are better ways to actually copy the contents of one file to another.

Upvotes: 3

Blindy
Blindy

Reputation: 67352

c=="" also won't work like you think it does.

Upvotes: 5

EFraim
EFraim

Reputation: 13028

Because character is not a string.

Try fputc.

BTW: The c should be int, otherwise you won't be able to detect EOF. EOF > 255.

Upvotes: 10

Related Questions