[RESOLVED] Segmentation fault and also bad initalization
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 18

Thread: [RESOLVED] Segmentation fault and also bad initalization

  1. #1

    [RESOLVED] Segmentation fault and also bad initalization

    Code:
    #include <sys/types.h>
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    
    #define FILEPATH "./input.txt"
    #define FILEPATH2 "./copy.txt"
     
    
    
    
    
    
    
    #define BUFFER_SIZE 25
    #define READ_END 0
    #define WRITE_END 1
    
    int main(void)
    {
    
    char* s;
    
    
      char read_msg[BUFFER_SIZE];
      int fd[2];
      pid_t pid;
      
       FILE *fp; 
       FILE *fp2;
      
       fp = fopen(FILEPATH, "r"); 
       
       if(!fp){
         fprintf(stderr, "File - %s - could not be opened.\n", FILEPATH);
         return -1;
       }
       
    s = fgets(s, 32766, fp); //ERROR HERE!!!
    
      /* create the pipe */
      if (pipe(fd) == -1){
        fprintf(stderr, "Pipe failed");
        return 1;
      }
      char write_msg[BUFFER_SIZE] = s;  //How do I get this value of s into the right format?
      /* fork a child process */
      pid = fork();
    
      if (pid < 0) { /* error occurred */
        fprintf(stderr, "Fork Failed");
        return 1;
      }
    
      if (pid > 0) { /* parent process */
        /* close the unused end of the pipe */
        close(fd[READ_END]);
    
        /* write to the pipe */
        write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
    
        /* close the write end of the pipe */
        close(fd[WRITE_END]);
      }
    
      else { /* child process */
        /* close the unused end of the pipe */
        close(fd[WRITE_END]);
    
        /* read from the pipe */
        read(fd[READ_END], read_msg, BUFFER_SIZE);
     //   printf("read %s", read_msg);
    fclose(fp);
    fp2 = fopen(FILEPATH2, "w");
    
    
       fwrite(read_msg, 32767, 32767, fp2);
       
    
        /* close the write end of the pipe */
        close(fd[READ_END]);
         fclose(fp2);
      }
    
      return 0;
    }
    The problem is probably the fact that I'm using the variable s in the wrong way, but as I'm very bad at C and C++, at least so far anyway, I've no clue what's wrong.

    Is it my size that I passed in the marked method?

    Also, how do I tell it, later, once this starts to work, to pass the file name of the file it'll copy to as the first param and the file it reads from to the pipe as the second param?

    I'm supposed to be reading from a file, and as I was given some help code, but it's probably in C and not C++, even if it is, I'm still not that great at C++ either, but anyway, I'm to have the program read from the file and write to the pipe and have the child read from the pipe and write to the output file.

    FileCopy copy.txt input.txt

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Segmentation fault and also bad initalization

    At the moment s is just an uninitialized pointer. It does not point to a valid block of memory, therefore you can't safely write anything to it.

    You will find it much, much easier to define s as a std::string and use the <iostream> library for reading/writing, than to fix the problem with s. Fixing the problem with s as it is would be pretty easy for someone who knows C well, but it doesn't sound like you do and thus you are likely to have trouble. The C++ string and IO methods are much more intuitive.

  3. #3

    Re: Segmentation fault and also bad initalization

    Well, unfortunately I'd need to find all the C++ header files that would correspond to the C ones that I got provided. But I wouldn't know what they were.

    Unless you could tell me all the libraries to correspond to the ones I have in C for C++, I can't go the C++ route. At least, I don't think I can......

    Is there another way I could intialize it without the circular logic?

    i.e.

    s = gets(s, int, File);
    Last edited by jedipenguin; February 25th, 2012 at 09:14 PM.

  4. #4

    Re: Segmentation fault and also bad initalization

    Ok, so I set the value of s just to see what happens. Still getting the segmentation fault. Is it my value of fp? I've no way to tell as when I tried to print out its value, I got like $ and weird blurs or something. Probably because fp is a pointer, but I even tried dereferencing it and it still showed those weird symbols. What's going wrong?

    Code:
    #include <sys/types.h>
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    
    #define FILEPATH "./input.txt"
    #define FILEPATH2 "./copy.txt"
     
    
    
    
    
    
    
    #define BUFFER_SIZE 25
    #define READ_END 0
    #define WRITE_END 1
    
    int main(int argc, const char* argv[])
    {
    
    char* s = "Empty";
    
    if (argc !=3)
    {
    printf("You're forgetting some of the arguments.");
    exit(1);
    }
      char read_msg[BUFFER_SIZE];
      int fd[2];
      pid_t pid;
      
       FILE *fp; 
       FILE *fp2;
      
       fp = fopen(argv[2], "r"); 
       
       
       if(!fp){
         fprintf(stderr, "File - &#37;s - could not be opened.\n", FILEPATH);
         return -1;
       }
       
       
       printf(s);
       exit(1);
       
    s = fgets(s, strlen(s), fp); //ERROR HERE!!!
    
      /* create the pipe */
      if (pipe(fd) == -1){
        fprintf(stderr, "Pipe failed");
        return 1;
      }
      char write_msg[BUFFER_SIZE] = "Testing";  //How do I get this value of s into the right format?
      /* fork a child process */
      pid = fork();
    
      if (pid < 0) { /* error occurred */
        fprintf(stderr, "Fork Failed");
        return 1;
      }
    
      if (pid > 0) { /* parent process */
        /* close the unused end of the pipe */
        close(fd[READ_END]);
    
        /* write to the pipe */
        write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
    
        /* close the write end of the pipe */
        close(fd[WRITE_END]);
      }
    
      else { /* child process */
        /* close the unused end of the pipe */
        close(fd[WRITE_END]);
    
        /* read from the pipe */
        read(fd[READ_END], read_msg, BUFFER_SIZE);
     //   printf("read %s", read_msg);
    fclose(fp);
    fp2 = fopen(FILEPATH2, "w");
    
    
       fwrite(read_msg, strlen(read_msg), 1, fp2);
       
    
        /* close the write end of the pipe */
        close(fd[READ_END]);
         fclose(fp2);
      }
    
      return 0;
    }
    Right now it is set to exit before it hits the segmentation fault.

  5. #5
    Join Date
    Apr 1999
    Posts
    27,427

    Re: Segmentation fault and also bad initalization

    Quote Originally Posted by jedipenguin View Post
    Well, unfortunately I'd need to find all the C++ header files that would correspond to the C ones that I got provided. But I wouldn't know what they were.
    The same headers are used. The only additional header file is for the string class.
    Code:
    #include <string>
    Regards,

    Paul McKenzie

  6. #6
    Join Date
    Apr 1999
    Posts
    27,427

    Re: Segmentation fault and also bad initalization

    Quote Originally Posted by jedipenguin View Post
    Ok, so I set the value of s just to see what happens. Still getting the segmentation fault.
    That is because "s" is a string-literal, and you cannot write to string literals.

    Here is a much simpler program:
    Code:
    int main()
    {
       char *s = "abc123";
       s[0] = 'x';
    }
    This program also crashes, and for the same reason your program crashes. The s is a string-literal, and I'm attempting to change the first character from 'a' to 'x'. Crash.

    Only writeable char arrays, and memory allocated from the heap can be modified.
    Code:
    int main()
    {
       char s[] = "abc123";
       s[0] = 'x';
    }
    This code now doesn't crash, since s is a writeable array of char.

    Regards,

    Paul McKenzie

  7. #7

    Re: Segmentation fault and also bad initalization

    What if I don't know the length of the array?

    I take it you mean I should use an array rather than a pointer...?

  8. #8
    Join Date
    Apr 1999
    Posts
    27,427

    Re: Segmentation fault and also bad initalization

    Quote Originally Posted by jedipenguin View Post
    What if I don't know the length of the array?
    Then you use std::vector.
    I take it you mean I should use an array rather than a pointer...?
    When you pass an array to a function, the name of the array acts as a pointer to the first element in the array.

    The bottom line is that you can't use string-literals and then later on change or overwrite that literal in any way.

    Regards,

    Paul McKenzie

  9. #9

    Re: Segmentation fault and also bad initalization

    It's saying exit(1) is not declared in this scope....

    I told it to exit if it can't find the input files or things like that.

    Also, how what will the string do?

    Will I need to convert it to a cstring at some point?

    Also, the c++ library online is sometimes having server errors and I can't always access the documentation.



    Code:
    
    #include <sys/types.h>
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include<string>
    #include<vector>
    #include<iostream>
    #include <fstream>
    #include <sstream>
    
    #define FILEPATH "./input.txt"
    #define FILEPATH2 "./copy.txt"
     
    
    
    
    
    
    
    #define BUFFER_SIZE 25
    #define READ_END 0
    #define WRITE_END 1
    using namespace std;
    int main(int argc, const char* argv[])
    {
    
    ifstream input(argv[2]);
    string s2;
    
    vector<char> s;
    
    if (argc !=3)
    {
    printf("You're forgetting some of the arguments.");
    return 1;
    }
    
    
    
    
      char read_msg[BUFFER_SIZE]; // need to redefine this as it might be causing the ouput to the file to be empty
      int fd[2];
      pid_t pid;
      
       FILE *fp; 
       FILE *fp2;
      
      //  fp = fopen(argv[2], "r"); 
       
       
      /* if(!fp){
         fprintf(stderr, "File - &#37;s - could not be opened.\n", FILEPATH);
         return -1;
       }
       */
       getline(input, s2);
       
       while (!input.eof())
       {
       getline(input, s2);
       
       }
       
       
       
       
    // s = fgets(s, strlen(s), fp); //ERROR HERE!!!
    
      /* create the pipe */
      if (pipe(fd) == -1){
        fprintf(stderr, "Pipe failed");
        return 1;
      }
      const char* write_msg = s2.c_str();  //How do I get this value of s into the right format?
      /* fork a child process */
      pid = fork();
    
      if (pid < 0) { /* error occurred */
        fprintf(stderr, "Fork Failed");
        return 1;
      }
    string pipeMessage;
    const char* pm2;
      if (pid > 0) { /* parent process */
        /* close the unused end of the pipe */
        close(fd[READ_END]);
    
        /* write to the pipe */
        write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
    
        /* close the write end of the pipe */
        close(fd[WRITE_END]);
      }
    
    
      else { /* child process */
        /* close the unused end of the pipe */
        close(fd[WRITE_END]);
    
        /* read from the pipe */
       pm2 =  read(fd[READ_END], read_msg, strlen(read_msg) + 1);
        printf("read %s", read_msg);
        
     //   printf("read %s", read_msg);
    // fclose(fp);
    
    ofstream output(argv[1]);
    
    
    
       output << read_msg;
       
       output.close();
       
    
        /* close the write end of the pipe */
        close(fd[READ_END]);
         // fclose(fp2);
      }
    
      return 0;
    }
    It's creating copy.txt but there's nothing in it.

    Also, it won't let me read in the value for read message or whatever from the pipe. What's going wrong?
    Last edited by jedipenguin; February 26th, 2012 at 04:24 PM.

  10. #10

    Unhappy Re: Segmentation fault and also bad initalization

    This writes only 1 character. When I tell it to read in multiple times, i.e. many getlines, it gets nothing at all. I'm very frustrated!


    Code:
    #include <sys/types.h>
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include<string>
    #include<vector>
    #include<iostream>
    #include <fstream>
    #include <sstream>
    
    #define FILEPATH "./input.txt"
    #define FILEPATH2 "./copy.txt"
     
    
    
    
    
    
    
    #define BUFFER_SIZE 25
    #define READ_END 0
    #define WRITE_END 1
    using namespace std;
    int main(int argc, const char* argv[])
    {
    
    ifstream input(argv[2]);
    
    if (!input.is_open())
    {
    printf("File is busted!");
    return 1;
    }
    string s2;
    
    vector<char> s;
    
    if (argc !=3)
    {
    printf("You're forgetting some of the arguments.");
    return 1;
    }
    
    
    
    
      char read_msg[BUFFER_SIZE];
      int fd[2];
      pid_t pid;
      
       FILE *fp; 
       FILE *fp2;
      
      //  fp = fopen(argv[2], "r"); 
       
       
      /* if(!fp){
         fprintf(stderr, "File - &#37;s - could not be opened.\n", FILEPATH);
         return -1;
       }
       */
       
       
     getline(input, s2);
     cout << s2;
       
       
       
       
       
       
    // s = fgets(s, strlen(s), fp); //ERROR HERE!!!
    
      /* create the pipe */
      if (pipe(fd) == -1){
        fprintf(stderr, "Pipe failed");
        return 1;
      }
      
      printf(s2.c_str());
      const char* write_msg = s2.c_str();  //How do I get this value of s into the right format?
      /* fork a child process */
      pid = fork();
    
      if (pid < 0) { /* error occurred */
        fprintf(stderr, "Fork Failed");
        return 1;
      }
    string pipeMessage;
    const char* pm2;
      if (pid > 0) { /* parent process */
        /* close the unused end of the pipe */
        close(fd[READ_END]);
        printf(write_msg);
        /* write to the pipe */
        write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
        printf(write_msg);
        /* close the write end of the pipe */
        close(fd[WRITE_END]);
      }
    
    
      else { /* child process */
        /* close the unused end of the pipe */
        close(fd[WRITE_END]);
    
        /* read from the pipe */
        
        read(fd[READ_END], read_msg, strlen(read_msg) + 1);
        printf("read %s", read_msg);
        
     //   printf("read %s", read_msg);
    // fclose(fp);
    
    ofstream output(argv[1]);
    
    
    
       output << read_msg;
       
       output.close();
       
    
        /* close the write end of the pipe */
        close(fd[READ_END]);
         // fclose(fp2);
      }
    
      return 0;
    }
    Last edited by jedipenguin; February 26th, 2012 at 04:55 PM.

  11. #11
    Join Date
    Apr 1999
    Posts
    27,427

    Re: Segmentation fault and also bad initalization

    Quote Originally Posted by jedipenguin View Post
    This writes only 1 character. When I tell it to read in multiple times, i.e. many getlines, it gets nothing at all.
    First, it would help if your code was formatted much better, as it is hard to read as it stands now.
    Code:
    #include <sys/types.h>
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include<string>
    #include<vector>
    #include<iostream>
    #include <fstream>
    #include <sstream>
    
    #define FILEPATH "./input.txt"
    #define FILEPATH2 "./copy.txt"
    #define BUFFER_SIZE 25
    #define READ_END 0
    #define WRITE_END 1
    using namespace std;
    
    int main(int argc, const char* argv[])
    {
        ifstream input(argv[2]);
        if (!input.is_open())
        {
            printf("File is busted!");
            return 1;
        }
        string s2;
        vector<char> s;
    
        if (argc !=3)
        {
            printf("You're forgetting some of the arguments.");
            return 1;
        }
    
        char read_msg[BUFFER_SIZE];
        int fd[2];
        pid_t pid;
          
        FILE *fp; 
        FILE *fp2;
      
        getline(input, s2);
        cout << s2;
    
        /* create the pipe */
        if (pipe(fd) == -1)
        {
           fprintf(stderr, "Pipe failed");
           return 1;
        }
    
        printf(s2.c_str());
        const char* write_msg = s2.c_str();  //How do I get this value of s into the right format?
        /* fork a child process */
        pid = fork();
    
        if (pid < 0) { /* error occurred */
          fprintf(stderr, "Fork Failed");
          return 1;
        }
        string pipeMessage;
        const char* pm2;
        if (pid > 0) 
        { 
            close(fd[READ_END]);
            printf(write_msg);
            /* write to the pipe */
            write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
            printf(write_msg);
            /* close the write end of the pipe */
            close(fd[WRITE_END]);
        }
        else 
        { /* child process */
            close(fd[WRITE_END]);
            read(fd[READ_END], read_msg, strlen(read_msg) + 1);
            printf("read &#37;s", read_msg);
            ofstream output(argv[1]);
            output << read_msg;
            output.close();
            close(fd[READ_END]);
        }
        return 0;
    }
    Look at these lines:
    Code:
        char read_msg[BUFFER_SIZE];
        //...
        read(fd[READ_END], read_msg, strlen(read_msg) + 1);
    The strlen() is a function that requires that the array is null-terminated. The strlen() counts characters starting from the beginning of the buffer until NULL is encountered. Where is the NULL in an uninitialized char array such as read_msg? Who knows? It could be first character, or it could be the 1,000th character.

    Basically, you're calling strlen() on something that isn't initialized. To get the actual size of that array:
    Code:
    const int numChars = sizeof(read_msg) / sizeof(read_msg[0]);
    Then you use numChars instead of strlen().

    Regards,

    Paul McKenzie

  12. #12

    Re: Segmentation fault and also bad initalization

    Actually, the issue is probably where the s2 is read in at the beginning. The value of s2 is ok after the first getline() but after that, it suddenly becomes empty.
    Also, should I use the numChars also for the write() part as well?
    Code:
    
    #include <sys/types.h>
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    #include<string>
    #include<vector>
    #include<iostream>
    #include <fstream>
    #include <sstream>
    
    #define FILEPATH "./input.txt"
    #define FILEPATH2 "./copy.txt"
     
    
    
    
    
    
    
    #define BUFFER_SIZE 25
    #define READ_END 0
    #define WRITE_END 1
       using namespace std;
       int main(int argc, const char* argv[])
       {
       
          ifstream input(argv[2]);
       
          if (!input.is_open())
          {
             printf("File is busted!");
             return 1;
          }
          string s2;
       
          vector<char> s;
       
          if (argc !=3)
          {
             printf("You're forgetting some of the arguments.");
             return 1;
          }
       
       
       
       
          char read_msg[BUFFER_SIZE];
          int fd[2];
          pid_t pid;
       
          FILE *fp; 
          FILE *fp2;
       
       //  fp = fopen(argv[2], "r"); 
       
       
       /* if(!fp){
         fprintf(stderr, "File - &#37;s - could not be opened.\n", FILEPATH);
         return -1;
       }
       */
       
       
          getline(input, s2);
       
          cout << s2;
          while (!input.eof())
          {
             getline(input, s2);
          }
       
       
       
       
       
       // s = fgets(s, strlen(s), fp); //ERROR HERE!!!
       
       /* create the pipe */
          if (pipe(fd) == -1){
             fprintf(stderr, "Pipe failed");
             return 1;
          }
       
          printf(s2.c_str());
          const char* write_msg = s2.c_str();  //How do I get this value of s into the right format?
          printf(write_msg);
          printf("\n");
       /* fork a child process */
          pid = fork();
       
          if (pid < 0) { /* error occurred */
             fprintf(stderr, "Fork Failed");
             return 1;
          }
          string pipeMessage;
          const char* pm2;
          if (pid > 0) { /* parent process */
          /* close the unused end of the pipe */
             close(fd[READ_END]);
             printf(write_msg);
          /* write to the pipe */
             write(fd[WRITE_END], write_msg, strlen(write_msg) + 1);
             printf(write_msg);
          /* close the write end of the pipe */
             close(fd[WRITE_END]);
          }
          
          
          else { /* child process */
          /* close the unused end of the pipe */
             close(fd[WRITE_END]);
          
          /* read from the pipe */
             const int numchars = sizeof(read_msg)/sizeof(read_msg[0]);
             read(fd[READ_END], read_msg, numchars);
             printf("read %s", read_msg);
          
          //   printf("read %s", read_msg);
          // fclose(fp);
          
             ofstream output(argv[1]);
          
          
             printf(read_msg);
          
             output << read_msg;
          
             output.close();
          
          
          /* close the write end of the pipe */
             close(fd[READ_END]);
          // fclose(fp2);
          }
       
          return 0;
       }
    The thing I'm using to compile only did formatting at a certain point in emacs. Once I stopped emacs, it woouldn't do it, even when I went back to emacs.

    I can't get C++ through netbeams as I don't know how to upload the files in order to run C++. the format can't really be improved. The above formatting is the best I can do.
    Last edited by jedipenguin; February 26th, 2012 at 05:29 PM.

  13. #13
    Join Date
    Apr 1999
    Posts
    27,427

    Re: Segmentation fault and also bad initalization

    Quote Originally Posted by jedipenguin View Post
    Actually, the issue is probably where the s2 is read in at the beginning. The value of s2 is ok after the first getline() but after that, it suddenly becomes empty.
    Code:
     getline(input, s2);
     cout << s2;
     while (!input.eof())
        getline(input, s2);
    So what is in that input file that makes s2 empty? Instead of trying different things and hoping something sticks, you should be using the debugger to debug your code, and then diagnose the problem from there.
    I can't get C++ through netbeams as I don't know how to upload the files in order to run C++. the format can't really be improved. The above formatting is the best I can do.
    Get yourself better tools, since I was able to format it within a few seconds. Or spend the time to post legible code since you want others to read it.

    Regards,

    Paul McKenzie

  14. #14

    Re: Segmentation fault and also bad initalization

    I've no earthly idea. Especially as it has read the string in at first but loses it after the while loop.

    All the file contains is:

    This is a message.
    This is a message.

    My first printf ouputs: This is a message.

    My second printf ouputs nothing.

    It's not a compiler error so the debugger won't get it.

    I don't have a fancy IDE. I have a simple LINUX program. Netbeams won't work and anyway, I'd have to export it to the LINUX thing to submit the assignment anyway.

    I don't have a debugger. Ok.
    Last edited by jedipenguin; February 26th, 2012 at 06:03 PM.

  15. #15
    Join Date
    Apr 1999
    Posts
    27,427

    Re: Segmentation fault and also bad initalization

    Quote Originally Posted by jedipenguin View Post
    It's not a compiler error so the debugger won't get it.
    Do you know what the debugger is? A debugger has nothing to do with the compiler.

    The debugger allows you to step through your program one line at a time. Then you can watch variables, set breakpoints, etc.

    Regards,

    Paul McKenzie

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center