Like Tree4Likes

Need help to get rid of segmentation fault

This is a discussion on Need help to get rid of segmentation fault within the C++ Programming forums, part of the General Programming Boards category; The sample line of the file "RedwoodBaySeismicEventList.data" looks like this : [Text] Alpha:01232012:0100:2.7 [/Text] Note: "Alpha" represents ID "01232012" represents ...

  1. #16
    Registered User
    Join Date
    Jun 2012
    Posts
    7
    The sample line of the file "RedwoodBaySeismicEventList.data" looks like this :

    [Text]

    Alpha:01232012:0100:2.7

    [/Text]

    Note:
    "Alpha" represents ID
    "01232012" represents Date
    "0100" represents Hour
    "2.7" represents Magnitude

    Also, sorry I forgot to indent the code earlier. So, here is the indented code below:

    Code:
        #include <iostream>
        #include <fstream>
        #include <string>
        #include <vector>
        #include <sstream>
        using namespace std;
        
        //Define a class to represent each Seismic Activity measurement event...
        
            class RedwoodBaySeismicData  {
              string LocationID;   //This is the station that owns this piece of data…
              string Date;     //The date that the values were collected…
              string Time;    //The time of day that the values were collected…
              double SeismicSize;  //Magnitude of Earthquake
              
            
            public:
              RedwoodBaySeismicData();
              RedwoodBaySeismicData(string, string, string, double);
            
              //The first group of member functions are used to change values...
              //Functions are defined in the form of inlines.
            
              void SetID(string ID)     { LocationID = ID; }
              void SetDate(string Day)   { Date = Day; }
              void SetTime(string Hour)   { Time = Hour; }
              void SetSeismicSize(double Magnitude) {SeismicSize = Magnitude; }
              
            
              //The second group allows controlled access to individual value in the class...
            
              string GetID()    { return LocationID; }
              string GetDate()   {return Date; }
              string GetTime()   {return Time; }
              double GetSeismicSize() { return SeismicSize;}  
              
             
            
            };
            
            
            
            //The default constructor sets the private variable members to a harmless value...
            
            RedwoodBaySeismicData::RedwoodBaySeismicData()
            {
             LocationID = "";
             Date = "";
             Time = "";
             SeismicSize = 0.0;
             
            }
            
            //This initializing  constructor allows you to create a object with value already set...
            
             RedwoodBaySeismicData::RedwoodBaySeismicData(string ID, string Day, string Hour, double Magnitude)
            {
             LocationID = ID;
             Date = Day;
             Time = Hour;
             SeismicSize = Magnitude;
             
            }
         
             class RedwoodBayDataList  {
             vector<RedwoodBaySeismicData> RedwoodBayDataSpots;  //Create a collection of location information...
                string FileName ;
             public:
             RedwoodBayDataList()  {FileName = "RedwoodBaySeismicEventList.data";}
            
                
            void PostSeismicInfo();
                
            };
             
         
         
            //Allow the user to post the values for each location...
        
            void RedwoodBayDataList::PostSeismicInfo()
            {
             int K;
             string Line, ID, Date, Hour;
             double Magnitude;
             fstream InFile("RedwoodBaySeismicEventList.data", ios::in);
             //...then get the values for each location...
             RedwoodBaySeismicData Buffer;
         
                cout << "\n\t=============================================================" << endl;  //This section is the report...it's really all about the formatting...
                cout << "\tWeekly Report" << endl;
                cout << "\t===============================================================" << endl;
                cout << "\tLocation\tDate\tHour\tMagnitude" << endl;
                cout << "\t===============================================================" << endl;
         
        
             for(size_t K = 0; K < RedwoodBayDataSpots.size(); ++K)  {
                      
              getline(InFile, Line);
              ID = Line.substr(0,4);
              Date =  Line.substr(6,7);
              Hour = Line.substr(9,3);
              istringstream buf(Line.substr(5,2));
              buf>> Magnitude;
                
              Buffer.SetID(ID);    //Use these values to load the Buffer record...
              Buffer.SetDate(Date); 
              Buffer.SetTime(Hour);
              Buffer.SetSeismicSize(Magnitude);
              RedwoodBayDataSpots.push_back(Buffer);
          
             
              RedwoodBayDataSpots[K].SetID(ID);
              RedwoodBayDataSpots[K].SetDate(Date);
              RedwoodBayDataSpots[K].SetTime(Hour);
              RedwoodBayDataSpots[K].SetSeismicSize(Magnitude);  
              cout << "\t" << RedwoodBayDataSpots[K].GetID() << "\t" << RedwoodBayDataSpots[K].GetDate() << "\t" << RedwoodBayDataSpots[K].GetTime() << "\t"  << RedwoodBayDataSpots[K].GetSeismicSize();
               }
              cout << "\t===============================================================\n\n" << endl;
        
         
               }
         
            
        
        //Declare the functions...
        
            void RunIT();
            void Menu();
             
            
            int main()
            {
             RunIT();
            }
        
        //This function implements a simple command processor...
        
            void RunIT()
            {
             RedwoodBayDataList RedwoodBayDataSpots;
             string Command = "";
        
             while(Command != "Quit")  {
              Menu();
              cout << "Command: ";
              getline(cin, Command);
         
              if(Command == "Report")
               RedwoodBayDataSpots.PostSeismicInfo();
             }
             }
        
        //This function tells the user what he or she can do...
        
            void Menu()
            {
             cout << "Choices...................................................." << endl;
             cout << "-----------------------------------------------------------" << endl;
             cout << "\tReport...displays the  report." << endl;
             cout << "\tQuit.....exits the program." << endl;
             cout << "-----------------------------------------------------------" << endl;
             }
    Last edited by torresdrogba; 06-18-2012 at 02:24 PM.

  2. #17
    Registered User
    Join Date
    May 2010
    Posts
    2,805
    Please post a small sample of your actual input file, with at least 5 to 10 entries.

    Jim

  3. #18
    Registered User
    Join Date
    Jun 2012
    Posts
    7
    Here is the sample of my actual input file:

    [text]

    Alpha:01232012:0100:2.7
    Alpha:01292012:0100:2.2
    Alpha:02022012:0100:2.1
    Alpha:02032012:0100:3.5
    Alpha:03012012:0100:5.4
    Alpha:03042012:0100:5.8
    Alpha:03112012:0100:5.7
    Alpha:03212012:0100:3.1
    Alpha:04052012:0100:2.8
    Alpha:04152012:0100:2.6
    Alpha:04162012:0100:1.3
    Alpha:04182012:0100:3.3
    Alpha:04222012:0100:3.7
    Alpha:05012012:0100:3.3
    Alpha:05012012:0100:4.5
    Alpha:05022012:0100:6.1
    Alpha:05032012:0100:6.0
    Alpha:05112012:0100:5.9
    Alpha:05122012:0100:6.4
    Alpha:06032012:0100:6.1
    Alpha:06142012:0100:5.9
    Alpha:06182012:0100:5.8
    Alpha:06222012:0100:5.2
    Beta:01232012:0100:3.7
    Beta:01292012:0100:3.2
    Beta:02022012:0100:3.1
    Beta:02032012:0100:4.5
    Beta:03012012:0100:4.4
    Beta:03042012:0100:4.8
    Beta:03112012:0100:4.7

    [/text]

    Thanks

  4. #19
    Registered User
    Join Date
    May 2010
    Posts
    2,805
    In your PostSeismicInfo() function in the following line:
    Code:
      for(size_t K = 0; K < RedwoodBayDataSpots.size(); ++K)  {
    When you first encounter this loop your vector contains zero items so K will be equal to the size, therefore the loop will never execute. Normally when you are reading an input file you use a while() loop and push the data into the vector after you read the line of information.


    Also because a std::string is a class to construct an empty instance you don't want to use the assignment operator. For example:
    Code:
       std::string test = ""; // This is not necessary.
       std::string test;       // This is the proper way to construct an empty string.
    When you use the assignment operator you cause the compiler to do extra steps, for example calling the copy constructor. And in a class constructor you don't actually need to construct an empty string member because the default constructor for a string is an empty string.


    Jim
    Last edited by jimblumberg; 06-18-2012 at 05:07 PM.

  5. #20
    Registered User
    Join Date
    Jun 2012
    Posts
    7
    Hi everyone. As per the advice, I have modified my code again. Now, I am using while loop to read the data from the file. However, my programme is still not running. Whenever I try to run the programme the dialog box appears and says "un.exe" has stopped working. By the way, I am usin DEV C++. Also, here is the modified version of the code:

    Code:
        #include <iostream>
        #include <fstream>
        #include <string>
        #include <vector>
        #include <sstream>
        using namespace std;
        
        //Define a class to represent each Seismic Activity measurement event...
        
            class RedwoodBaySeismicData  
            {
              string LocationID;   //This is the station that owns this piece of data…
              string Date;     //The date that the values were collected…
              string Time;    //The time of day that the values were collected…
              double SeismicSize;  //Magnitude of Earthquake
              
            
            public:
              RedwoodBaySeismicData();
              RedwoodBaySeismicData(string, string, string, double);
            
              //The first group of member functions are used to change values...
              //Functions are defined in the form of inlines.
            
              void SetID(string ID)     { LocationID = ID; }
              void SetDate(string Day)   { Date = Day; }
              void SetTime(string Hour)   { Time = Hour; }
              void SetSeismicSize(double Magnitude) {SeismicSize = Magnitude; }
              
            
              //The second group allows controlled access to individual value in the class...
            
              string GetID()    { return LocationID; }
              string GetDate()   {return Date; }
              string GetTime()   {return Time; }
              double GetSeismicSize() { return SeismicSize;}  
              
             
            
            };
            
            
            
            //The default constructor sets the private variable members to a harmless value...
            
            RedwoodBaySeismicData::RedwoodBaySeismicData()
            {
             LocationID;
             Date;
             Time;
             SeismicSize = 0.0;
             
            }
            
            //This initializing  constructor allows you to create a object with value already set...
            
             RedwoodBaySeismicData::RedwoodBaySeismicData(string ID, string Day, string Hour, double Magnitude)
            {
             LocationID = ID;
             Date = Day;
             Time = Hour;
             SeismicSize = Magnitude;
             
            }
         
            class RedwoodBayDataList 
            {
                 vector<RedwoodBaySeismicData> RedwoodBayDataSpots;  //Create a collection of location information...
                 string FileName ;
            public:
                 RedwoodBayDataList()  {FileName = "RedwoodBaySeismicEventList.data";}
                
                    
                 void PostSeismicInfo();
                
            };
             
         
         
            //Allow the user to post the values for each location...
        
                void RedwoodBayDataList::PostSeismicInfo()
            {
                 int K;
                 string Line, ID, Date, Hour;
                 double Magnitude;
                 fstream InFile("RedwoodBaySeismicEventList.data", ios::in);
                 //...then get the values for each location...
                 RedwoodBaySeismicData Buffer;
         
                 cout << "\n\t=============================================================" << endl;  //This section is the report...it's really all about the formatting...
                 cout << "\tWeekly Report" << endl;
                 cout << "\t===============================================================" << endl;
                 cout << "\tLocation\tDate\tHour\tMagnitude" << endl;
                 cout << "\t===============================================================" << endl;
         
                 
                          
                  while (!InFile.eof())            
                      
             { 
                  getline(InFile, Line);
                  ID = Line.substr(0,4);
                  Date =  Line.substr(6,7);
                  Hour = Line.substr(9,3);
                  istringstream buf(Line.substr(5,2));
                  buf>> Magnitude;
                
                  Buffer.SetID(ID);    //Use these values to load the Buffer record...
                  Buffer.SetDate(Date); 
                  Buffer.SetTime(Hour);
                  Buffer.SetSeismicSize(Magnitude);
                  RedwoodBayDataSpots.push_back(Buffer);
          
                  for(K = 0 ; K < RedwoodBayDataSpots.size(); ++K)  
                  {
                  RedwoodBayDataSpots[K].SetID(ID);
                  RedwoodBayDataSpots[K].SetDate(Date);
                  RedwoodBayDataSpots[K].SetTime(Hour);
                  RedwoodBayDataSpots[K].SetSeismicSize(Magnitude);  
                  cout << "\t" << RedwoodBayDataSpots[K].GetID() << "\t" << RedwoodBayDataSpots[K].GetDate() << "\t" << RedwoodBayDataSpots[K].GetTime() << "\t"  << RedwoodBayDataSpots[K].GetSeismicSize();
                  }
                  cout << "\t===============================================================\n\n" << endl;
                  }
                  InFile.close();
        
        
              }
            
        
        //Declare the functions...
        
              void RunIT();
              void Menu();
             
           
              int main()
              {
              RunIT();
              }
        
        //This function implements a simple command processor...
        
              void RunIT()
              {
              RedwoodBayDataList RedwoodBayDataSpots;
              string Command;
        
              while(Command != "Quit")  {
              Menu();
              cout << "Command: ";
              getline(cin, Command);
         
               if(Command == "Report")
               RedwoodBayDataSpots.PostSeismicInfo();
               }
               }
        
        //This function tells the user what he or she can do...
        
              void Menu()
              {
              cout << "Choices...................................................." << endl;
              cout << "-----------------------------------------------------------" << endl;
              cout << "\tReport...displays the  report." << endl;
              cout << "\tQuit.....exits the program." << endl;
              cout << "-----------------------------------------------------------" << endl;
              }
    As always, I would greatly appreciate any suggestions.
    Last edited by torresdrogba; 06-18-2012 at 08:25 PM.

  6. #21
    Registered User
    Join Date
    May 2010
    Posts
    2,805
    First since you are getting a segmentation fault, have you run the program through your debugger? The debugger will tell you exactly where the problem is detected, and you can view the variables at the time of the crash to help determine the cause of the crash.

    My first suggestion is to insure your file is opening correctly. Next you should check the FAQ for information as to why you should not use eof() to control an input loop. I recommend using getline() for controlling the loop:
    Code:
    while(getline(inputFile, string))
    Where inputFile is your file stream instance and string is a "buffer" for processing the line. The above code will extract one line at time from a file until the end of file. If the getline() fails for any reason then the loop will end.

    I also think you should think about starting your file reading function again. First read one line from the file and verify that you have indeed read the file correctly. Then after you insure you are reading one line correctly use a istringstream to parse this line. Think about using getline() with the optional third parameter to extract your Id, date, and time using the colon as the delimiter. Lastly use the extraction operator>> to extract the magnitude value. Verify that you have indeed extracted each item correctly before you move to the next extraction operation. Once you have successfully extracted one line into individual strings and doubles you can then create an instance of your class to insert into your vector.

    Jim
    rags_to_riches likes this.

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I don't know the cause of this segmentation fault
    By Dante McDaniels in forum C Programming
    Replies: 3
    Last Post: 02-05-2012, 01:35 AM
  2. Segmentation Fault
    By Dansas in forum C Programming
    Replies: 3
    Last Post: 11-21-2008, 01:12 PM
  3. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  4. Segmentation Fault
    By jat421 in forum C Programming
    Replies: 6
    Last Post: 04-03-2005, 02:26 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 10:09 PM

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