Can't find the cause of a segmentation fault

This is a discussion on Can't find the cause of a segmentation fault within the C++ Programming forums, part of the General Programming Boards category; Our lab for class today was this simple program, but I got a segmentation fault somewhere. After trying everything listed ...

  1. #1
    Moderately Rabid Decrypt's Avatar
    Join Date
    Feb 2005
    Location
    Milwaukee, WI, USA
    Posts
    300

    Can't find the cause of a segmentation fault

    Our lab for class today was this simple program, but I got a segmentation fault somewhere. After trying everything listed below, neither I nor my TA could figure it out! Any ideas?

    Code:
    //Lab Exercise 3
    //lab3.cpp
    
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    
    using namespace std;
    
    void selection_sort(int[], int);
    
    int main()
    {
       ifstream infile;
    
       int numbers[100];
       char in_file_name[16];
    
       cout << "Integer Sort\n"
            << "------------\n" //seg fault 1
    
            << "Please enter the filename to sort: ";
       
       cin >> in_file_name;
    //seg fault 2
    cout << in_file_name;
    
    cout << "opening file..."<<endl;
       infile.open(in_file_name);
    
    cout << "opening file...";
    
       if (infile.fail())
       {
          cout <<  "Error opening file.  Please try again.\n";
          exit (1);
       }
    
    cout<<"Adios";
    
       int count = 0;
    
    cout << "Inputting...";
    
       while ((infile >> numbers[count])  && (count < 50))
          ++count;
    
    cout << "Sorting...";
       selection_sort(numbers, count);
       
       ofstream outfile;
       outfile.open("sorted.txt");
    
       for (int i = 0; i < count; ++i)
          outfile << numbers[[i];
    
       cout << "The sorted numbers have been written to sorted.txt." 
              << "Have a nice day!\n"<<endl;
    
       infile.close();
       outfile.close();
       return 0;
    }
    Please forgive the odd indenting. The unindented cout statements are for debugging only. I don't indent them so they are easy to remove later.

    //seg fault 1 happened when I hardcoded the input filename, like:
    Code:
    istream infile;
    infile.open("int.txt");
    instead of asking the user for input.

    The file as is seg faults at //seg fault 2.

    Now comes the really weird part. If I input a file that does not exist, it acts properly. That is, it outputs the error message as described and exits the program. It does not give me a segmentation fault at all.

    Weird #2 - When the filename is hardcoded, and I combine the three separate string literals when asking for the filename to look like:
    Code:
    cout << "Integer Sort\n------------\nPlease enter blah blah blah";
    it still seg faults at //seg fault 1, right in the middle of outputting a string literal! The output is:
    Code:
    Integer Sort
    ------------
    <segmentation fault> core dumped  <--this isn't the exact message, but you get the idea
    Weird #3 - If I add endl's to a cout statement, I can make it to the next cout before it crashes. So if I add endls to the request for input, outputting in_file_name, and the lines
    Code:
     cout << "Opening file...";
    and
    Code:
    cout << "Adios";
    it will run that far, but crash somewhere before
    Code:
    cout << "Inputting...";
    and if I add and endl to that line, I make it to
    Code:
    cout << "Sorting...";
    before I crash.

    In my search of the board I found references to permission, which shouldn't be the case (I think), since a) no one else in the class experienced this, and b) I can view the file with "more int.txt" from my directory. I am working in UNIX, of which I have almost no knowledge. I don't think I'm accessing parts of my arrays I shouldn't be, and even if I were I don't imagine it'd give me this kind of behavior. FYI, this is not for credit anymore since the lab is over, so I don't think it falls under the homework clause. I removed the selection sort function to shorten this already-too-long post. I can post that, too, if need be.
    There is a difference between tedious and difficult.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    You must add endl (or flush) to all of your debugging statements. Just because you cout something doesn't mean it gets output to the screen. You must flush the output buffer to get it to show up. Both endl and flush automatically flush the buffer, and the buffer is flushed when you wait for input from cin and other seemingly random times. Therefore, to get the most out of your cout debug statements, always add the endl.

    The actual segmentation fault is most likely in your selection_sort code.

  3. #3
    Moderately Rabid Decrypt's Avatar
    Join Date
    Feb 2005
    Location
    Milwaukee, WI, USA
    Posts
    300
    >The actual segmentation fault is most likely in your selection_sort code.
    You're probably right, I looked it over (can't test it at work) and in one for loop I'm incrementing the wrong variable, which can only be trouble.

    I seem to recall hearing that segmentation faults are a colossal pain because they are hard to pin down sometimes, but how in the [insert your favorite expletive] can it cause a problem if I'm not overstepping an array or accessing forbidden memory at the time? I'm in the middle of outputting a string for [insert favorite saint or holy figure]'s sake! In the case of //seg fault 1, all I've done is declare the array in question - I haven't accessed or referenced it in any way!

    I'm not disputing that this is the trouble. I'm sure that for loop is it. I just don't get how it crashed from an error in that function if I haven't really dealt with any of the variables used in the function, let alone the function itself at the time it creates a segmentation fault.

    Also, why don't I need to use endl when outputting normally? (or do I?)
    Code:
    #include<iostream>
    int main()
    {
       std::cout << "Hello, world!";
       return 0;
    }
    works without endl...or is it printed to the screen by flushing the output buffer in some way unknown to me?
    There is a difference between tedious and difficult.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    >> I'm in the middle of outputting a string

    No, you're not. Remember, the seg fault is not happening during the output. It is happening later in the code, but because your output from earlier isn't written to the console right away, it appears as if it is happening during the output. Calling cout just stores the output in a buffer. Later, while the rest of your code is executing (for example, while your selection_sort code is executing), the contents of the buffer are displayed in the console.

    That is why putting endl or flush in the debug code is necessary, because otherwise you don't know whether that line executed or not.

    In your simple example, the output buffer is flushed upon the program's successful completion, probably in the destructor of cout or something like that.

  5. #5
    Moderately Rabid Decrypt's Avatar
    Join Date
    Feb 2005
    Location
    Milwaukee, WI, USA
    Posts
    300
    oooooooooohhhhhh.

    I get it.

    Daved, I don't mean to hump your leg or anything, but you. are. awesome. Thanks.
    There is a difference between tedious and difficult.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fscanf causes a SEGMENTATION FAULT
    By yougene in forum C Programming
    Replies: 15
    Last Post: 12-28-2008, 11:11 PM
  2. Segmentation fault problem
    By odedbobi in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2008, 02:36 AM
  3. Why am I getting segmentation fault on this?
    By arya6000 in forum C++ Programming
    Replies: 6
    Last Post: 10-12-2008, 06:32 AM
  4. segmentation fault... first time with unix...
    By theMethod in forum C Programming
    Replies: 16
    Last Post: 09-30-2008, 02:01 AM
  5. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21