Thread: segmentation fault (core dumped) error!

  1. #1
    Registered User
    Join Date
    Sep 2015
    Posts
    5

    segmentation fault (core dumped) error!

    segmentation fault (core dumped) comes when i compile the below code:
    Code:
    #include<stdio.h>  
    void main(void){      
    
           FILE *fp1,*fp2;     
           fp1=fopen("file1","r"); 
           fp2=fopen("file2","w");     
           char ch;     
    
           while((ch=fgetc(fp1))!=EOF){         
                  fputc(ch,fp2);     
           } 
    }

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    Quote Originally Posted by Seyed Basim View Post
    segmentation fault (core dumped) comes when i compile the below code:
    Code:
    #include<stdio.h>  
    void main(void){      
    
           FILE *fp1,*fp2;     
           fp1=fopen("file1","r"); 
           fp2=fopen("file2","w");     
           char ch;     
    
           while((ch=fgetc(fp1))!=EOF){         
                  fputc(ch,fp2);     
           } 
    }
    main() should be defined to return an int.
    Code:
    int main(void) { ... }
    When fixed, the code compiles fine. You don't get a seg fault on compile, but you would when you run the code if "file1" does not exist.

  3. #3
    Registered User
    Join Date
    Sep 2015
    Posts
    5
    Thank you, it works now (Y)

  4. #4
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,110
    To add, you always need to check the return value from any of the buffered I/O functions, especially the open, read, and write functions. That would have shown up the missing file when trying to open a non-existent file.

  5. #5
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    Also, fgetc() returns an int, so your variable "ch" should be an int too.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault (core dumped) error
    By Ph0x in forum C Programming
    Replies: 2
    Last Post: 09-29-2014, 03:37 PM
  2. Error: Segmentation fault (core dumped)
    By eiger3970 in forum C Programming
    Replies: 2
    Last Post: 10-25-2013, 03:17 AM
  3. Segmentation Fault(core dumped) error
    By gamers18 in forum C Programming
    Replies: 5
    Last Post: 12-05-2012, 01:53 PM
  4. ERROR: segmentation fault (core dumped)
    By sunny543 in forum C Programming
    Replies: 2
    Last Post: 08-23-2012, 03:07 AM
  5. Help with 'Segmentation fault (core dumped)' error?
    By Von Fuzzball in forum C Programming
    Replies: 12
    Last Post: 05-03-2011, 02:29 PM

Tags for this Thread