Thread: segmentation fault

  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    26

    segmentation fault

    This is very weird, I have checked many times and still think that there is nothing wrong, but I got a message of segmentation fault. Can someone explain to me or correct my code.
    Code:
    #include "stdio.h"
    Code:
    int main()
    {
      getKey();
    return0;
    }
    
    void getKey()
    {
      FILE *fp, *fp2;//, *fp3;
    char line[100] = "#the following key is for lastfirst\n";
      char content[1206], *z;
      fp = popen("ssh-keygen -t rsa -N \'\' -q -f lastfirst", "w");
      fp2 = fopen("lastfirst.pub", "r");
    // fp3 = fopen("lastfirst.temp", "w");
    //fprintf(fp3, line);
    
    
      z = fgets(content, sizeof(content), fp2);
      while(z!=EOF)
        {
          printf("%s", content);
        }
    
    
      fclose(fp2);
    //printf("%s", "end it");
      pclose(fp);
    //  fclose(fp2);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You should:
    • Indent your code properly.
    • #include <stdio.h> instead of "stdio.h" although #include "stdio.h" can work.
    • Declare your functions prior to their point of use.
    • Check that popen and fopen succeeded before proceeding to use the FILE pointers returned.
    • Check that fgets returned non-NULL rather than non-EOF, and you don't need a loop for that here.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jul 2012
    Posts
    26
    To encourage a positive discussion, I want to clean up my code a bit. I think the major issue is in fget() and I don't know what is wrong.
    Code:
    int main()
    {
      getKey();
    return0;
    }
    
    
    void getKey()
    {
      FILE *fp, *fp2;//, *fp3;
    char line[100] = "#the following key is for lastfirst\n";
      char content[1206], *z;
      fp = popen("ssh-keygen -t rsa -N \'\' -q -f lastfirst", "w");
      fp2 = fopen("lastfirst.pub", "r");
      z = fgets(content, sizeof(content), fp2);
    if(z!=EOF)
        {
          printf("%s", content);
        }
      fclose(fp2);
    pclose(fp);
    }

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by sharonch
    To encourage a positive discussion, I want to clean up my code a bit. I think the major issue is in fget() and I don't know what is wrong.
    In post #2, I already gave you a bunch of ways to improve your program. If you had followed up, you would have corrected your program to something like this:
    Code:
    #include <stdio.h>
    
    void getKey(void);
    
    int main(void)
    {
        getKey();
        return 0;
    }
    
    void getKey(void)
    {
        FILE *fp, *fp2;
        char line[100] = "#the following key is for lastfirst\n";
        char content[1206];
    
        fp = popen("ssh-keygen -t rsa -N \'\' -q -f lastfirst", "w");
        if (!fp)
        {
            fprintf(stderr, "Could not run ssh-keygen\n");
            return;
        }
    
        fp2 = fopen("lastfirst.pub", "r");
        if (!fp2)
        {
            fprintf(stderr, "Could not open public key file\n");
            pclose(fp);
            return;
        }
    
        if (fgets(content, sizeof(content), fp2))
        {
            printf("%s", content);
        }
    
        fclose(fp2);
        pclose(fp);
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > fp = popen("ssh-keygen -t rsa -N \'\' -q -f lastfirst", "w");
    > fp2 = fopen("lastfirst.pub", "r");
    Why exactly are you using popen here?

    Are you perhaps expecting ssh-keygen to finish writing to the file (presumably called lastfirst.pub) before the actual fopen() call in the next line?

    popen() is used when you want to communicate with the process you're running.
    If you just want it to do it's job, and then return when it's done, then use system()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Jul 2012
    Posts
    26
    Ok,
    I see the problem. It is a logic issue. The public key is not generated until the program finish. Therefore, it can't read or write while the file is not ready yet.

  7. #7
    Registered User
    Join Date
    Jul 2012
    Posts
    26
    Yes, system is working. Thank Salem.

  8. #8
    Registered User
    Join Date
    Jul 2012
    Posts
    26
    Something weird happened. I am running this code from a different directory and it is giving me segmentation fault again. Is it mean that I can't change directory in the system()?

    Code:
    #include <stdio.h>
    int main()
    {
      getKey();
      return 0;
    }
    
    void getKey()
    {
      FILE *fp, *fp2;
      char line[100] = "#\n#the following key is for lastfirst\n#\n";
      char content[1206];
      system
          ("cd /home/user/.ssh;pwd | ssh-keygen -t rsa -N \'\' -q -f lastfirst",
           "w");
    
      fp2 = fopen("lastfirst.pub", "r");
      if (!fp2) {
        fprintf(stderr, "no xxx.pub\n");
        fclose(fp2);
        return;
      }
      if (fgets(content, sizeof(content), fp2)) {
        printf("%s", content);
      }
      fp = fopen("lastfirst.pub", "a+");
      fprintf(fp, line);
      fprintf(fp, content);
      fclose(fp2);
    }
    Last edited by Salem; 07-16-2012 at 12:55 AM. Reason: Fixed code tags - STOP using whatever you use to colour text with useless font and colour tags

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    First, start compiling with more warnings enabled and pay attention to them.
    Code:
    $ gcc -W -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:4:3: warning: implicit declaration of function ‘getKey’ [-Wimplicit-function-declaration]
    foo.c: At top level:
    foo.c:8:6: warning: conflicting types for ‘getKey’ [enabled by default]
    foo.c:4:3: note: previous implicit declaration of ‘getKey’ was here
    foo.c: In function ‘getKey’:
    foo.c:14:7: warning: implicit declaration of function ‘system’ [-Wimplicit-function-declaration]
    foo.c:27:3: warning: format not a string literal and no format arguments [-Wformat-security]
    foo.c:28:3: warning: format not a string literal and no format arguments [-Wformat-security]
    > foo.c:14:7: warning: implicit declaration of function ‘system’ [-Wimplicit-function-declaration]
    Which is important, because you're passing it TWO PARAMETERS and it expects only one.

    > foo.c:27:3: warning: format not a string literal and no format arguments [-Wformat-security]
    > foo.c:28:3: warning: format not a string literal and no format arguments [-Wformat-security]
    If line or content have a % character, you're screwed.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    Jul 2012
    Posts
    26
    I can see why you say that for the line 27 and 28, but I think it is the only way for me to paste those info into a file.
    although the % is going to messup my program, I went into the lastfirst.pub to make sure there is no %. Therefore, the code should be ok for sometimes. But the segmentation happened because fp2==NULL. Why?

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > fprintf(stderr, "no xxx.pub\n");
    > fclose(fp2);

    Don't try and close it if it failed to open!

    > I went into the lastfirst.pub to make sure there is no %. Therefore, the code should be ok for sometimes
    That's not the problem.
    The problem is if you start doing the wrong thing as a matter of habit, you'll find out the hard way sometime later on in another program where it DOES matter.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User
    Join Date
    Mar 2011
    Posts
    546
    sharonch, when you ignore what Laserlight and Salem tell you and insist on doing it wrong, you are making a mistake.

  13. #13
    Registered User
    Join Date
    Jul 2012
    Posts
    26
    I think I have correct the warning. No segmentation faults, but now the "line" and "content" is not writing to where it suppose to.
    Code:
    #include <stdio.h>
    Code:
    int main()
    {
      getKey();
      return0;
    }
    void getKey()
    {
      FILE *fp, *fp2;
      char line[100] = "#\n#the following key is for lastfirst\n#\n";
      char content[1206];
      system("cd /home/user/.ssh/;pwd | ssh-keygen -t rsa -N \'\' -q -f lastfirst");
      if(fp2 = fopen("lastfirst.pub", "r"))
        {
          for(content; !feof(fp2); fscanf(fp2, "%s", content));
          fclose(fp2);
        }else{  return;  }
    
      fp = fopen("lastfirst.pub", "w+");
          fprintf(fp, "%s", line);
          fprintf(fp, "%s", content);
      fclose(fp); 
    return;
    }
    Last edited by sharonch; 07-16-2012 at 01:04 PM.

  14. #14
    Lurker
    Join Date
    Dec 2004
    Posts
    296
    Quote Originally Posted by sharonch View Post
    I think I have correct the warning. No segmentation faults, but now the "line" and "content" is not writing to where it suppose to.
    Code:
    #include <stdio.h>
    Code:
    int main()
    {
      getKey();
      return0;
    }
    void getKey()
    {
      FILE *fp, *fp2;
      char line[100] = "#\n#the following key is for lastfirst\n#\n";
      char content[1206];
      system("cd /home/user/.ssh/;pwd | ssh-keygen -t rsa -N \'\' -q -f lastfirst");
      if(fp2 = fopen("lastfirst.pub", "r"))
        {
          for(content; !feof(fp2); fscanf(fp2, "%s", content));
          fclose(fp2);
        }else{  return;  }
    
      fp = fopen("lastfirst.pub", "w+");
          fprintf(fp, "%s", line);
          fprintf(fp, "%s", content);
      fclose(fp); 
    return;
    }
    That code does not even compile. Read every post so far carefully, heed the advice given, post code that at least compiles without warnings and then maybe we'll bother to look at you code again.

    If you don't want to do the work, why should we?

  15. #15
    Registered User
    Join Date
    Jul 2012
    Posts
    26
    Quote Originally Posted by Jimmy View Post
    That code does not even compile.
    It compiled. Your statement is not true.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault?
    By onako in forum C++ Programming
    Replies: 4
    Last Post: 04-26-2010, 10:51 PM
  2. Segmentation fault
    By phoneix_hallows in forum C Programming
    Replies: 8
    Last Post: 08-27-2009, 05:56 AM
  3. Segmentation fault
    By Buckshot in forum C++ Programming
    Replies: 14
    Last Post: 06-23-2005, 08:20 AM
  4. segmentation fault : ?????
    By gemini_shooter in forum C Programming
    Replies: 5
    Last Post: 06-06-2005, 02:18 AM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM