why am i getting a segmentation fault in my output?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nar0122
    New Member
    • Nov 2009
    • 11

    why am i getting a segmentation fault in my output?

    Code:
    //Nicholas Riseden
    //CSCI 3300
    //Assignment 4 Version 2
    
    #include "tree.h"
    #include "pqueue.h"
    #include <string>
    #include <fstream>
    #include <iostream>
    #include <stdio.h>
    #include "binary1.h"
    
    using namespace std;
    
    /*****************************************************************
    *                            buildTree                           *
    ******************************************************************
    * buildTree takes the array built from getFrequency and builds a *
    * tree that holds a character and its priority using the insert  *
    * function.                                                      *
    *                                                                *
    * For example, if the file reads "AAb" it creates a node for the *
    * character 'A' and stores its priority 2 for that node.         *
    *****************************************************************/
    Node* buildTree(int arrayOfInts[])
    {
    	PriorityQueue q;
    	for(int x = 0; x <= 255; x++)
    	{
    		if(arrayOfInts[x]!=0)
    		{			
    			Node* leaf = new Node((char)x);
    			insert(q, leaf, arrayOfInts[x]);
    		}
    	}
    
    	Node* t1,*t2;
    	int p1, p2;
    	remove(q, t1, p1);
    	
    	while(isEmpty(q)==false)
    	{
    	    remove(q,t2, p2);
    	    Node* t3 = new Node(t1, t2);
    	    insert(q, t3, (p1 +p2));
    	    remove(q, t1, p1);
    	}
    
    	return t1;
    }
    
    /*****************************************************************
    *                            getFrequency                        *
    ******************************************************************
    * getFrequency takes an array of 256 integers.  It opens a       *
    * file and counts the amount of character                        *
    * frequencies that occur, storing that count into the position   *
    * in the array that correpsonds with the character's             *
    * Ascii value.                                                   *
    *                                                                *
    * For example, if the file reads "AAb" it stores the number 2 in *
    * position 64 in the array since capital A is a 65 on the Ascii  *
    * chart and arrays are zero based.                               *
    *****************************************************************/
    
    int* getFrequency(char* filename, int arrayOfInts[])
    {
    	ifstream in;
    	in.open(filename);
    	for(int i = 0; i < 256; i++)
    	{
    		arrayOfInts[i] = 0;
    	}
    
    
    	
    	int c = in.get();
    	
    	while(c!=EOF)
    	{
    		arrayOfInts[c]++;
    		c = in.get();
    	}
    
    	int count = 0;
    	cout<<"\nThe character frequencies are: \n\n";
    	int k = 0;
    	while(k < 256)
    	{
    
    		if(k>0)
    		{
    
    			if(k == 10)
    			{
    				cout<<"\\n "<<arrayOfInts[k]<<"\n";
    			}
    			else if(k!=10)
    			{
    			cout<<char(k)<< " "<<arrayOfInts[k]<<"\n";
    			}
    		}
    		
    	
    	count++;
    	cout<<"count is "<<count<<"\n";//count reaches 256, then segmentation fault is printed
    	k++;
    	}
    	
    	in.close();
    	cout<<"This is sparta\n";
    	return arrayOfInts;
    	cout<< "This is over\n";
    	
    }
    
    //comments to describe this function
    void writeTree(BFILE* f, Node* t)
    {  
    		if(t->kind!=leaf)
    		{
    			writeBit(f, 0);
    			writeTree(f, t->left);
    			writeTree(f, t->right);
    		}
    		else
    		{
    			writeBit(f, 1);
    			writeByte(f, t->ch);
    		}
    	
    	
    }
    //buildcode
    void buildCode(Node* n, string codeArray[], string pref)
    {
    	if(n->kind == leaf)
    	{	
    		codeArray[int(n->ch)] = pref;
    	}
    	else if(n->kind == nonleaf)
    	{
    		buildCode(n->left, codeArray, pref + "0");
    		buildCode(n->right, codeArray, pref + "1");
    	}
    	
    }
    //writecode(f, str) writes string str to BFILE* f, one bit
    //at a time.
    void writeCode(BFILE* f, string str)
    {
    		int y = str.length();
    		for(int x = 0; x < y; x++)
    		{
    			writeBit(f, str[x]);
    		}
    	
    }
    
    //function description
    void writeCodedFile(char* filename, string codearray[], BFILE* f)
    {
    	ifstream in;
    	in.open(filename);
    		int c = cin.get();
    		while(c != EOF)
    		{
    			writeCode(f, codearray[c]);
    			c = cin.get();
    		}
    cout<<"Test E";
    	in.close();
    }
    
    
    int main(int argc, char* argv[])
    {
            string codeArray[255];
    	int arrayOfInts[255];
    	int* frequencyArray = getFrequency(argv[1], arrayOfInts);//problem is here
    	cout<<"I am about to do buildTree.";//this never gets printed
    	Node* n = buildTree(frequencyArray);
    	cout<<"I am done buildTree.";//this never gets printed
    	buildCode(n, codeArray, "");
    
    	BFILE* f = openBinaryFileWrite(argv[2]);
    
    	writeTree(f,n);
    
    	writeCodedFile(argv[1], codeArray,f);
    
    	closeBinaryFileWrite(f);
    
    	return 0;
    
    }
    Last edited by Frinavale; Dec 8 '09, 09:45 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    In the future could you please only post the code that is relevant to the problem. It's unfair to expect people to sift through tons of code to find the few lines that you are having problems with.

    Also, in the future, please specify what you are having problems with, what (if any) errors you are getting, and what you have tried to solve the problem. Don't just post a bunch of code and expect us to figure out what it is, what's wrong with it, and what you are having problems with.

    Please check out the posting guidelines for more information on how to ask a question.


    A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).


    This means that somewhere in your code you are attempting to access memory that your application is not allowed to access. It's likely that you're moving through an array and going past the end of it...

    -Frinny

    Comment

    • Airslash
      New Member
      • Nov 2007
      • 221

      #3
      never mind my post, reshifted your code and my comment was incorrect.
      Try providing the error message and line number if possible, helps alot

      Comment

      • jfwfmt
        New Member
        • Nov 2009
        • 12

        #4
        check on whether char is signed or unsigned by default

        /s/ Jim WIlliams

        Comment

        • nar0122
          New Member
          • Nov 2009
          • 11

          #5
          I thought the whole code was necessary to understand what was going on. I apologize if anyone else other than "Frinny" had an issue with me posting. Anyways,here is the code where the actual problem was.
          Code:
          /*****************************************************************
          *                            getFrequency                        *
          ******************************************************************
          * getFrequency takes an array of 256 integers.  It opens a       *
          * file and counts the amount of character                        *
          * frequencies that occur, storing that count into the position   *
          * in the array that correpsonds with the character's             *
          * Ascii value.                                                   *
          *                                                                *
          * For example, if the file reads "AAb" it stores the number 2 in *
          * position 64 in the array since capital A is a 65 on the Ascii  *
          * chart and arrays are zero based.                               *
          *****************************************************************/
          
          int* getFrequency(char* filename, int arrayOfInts[])
          {
          	ifstream in;
          	in.open(filename);
          	for(int i = 0; i < 257; i++)
          	{
          		arrayOfInts[i] = 0;
          	}
          
          
          	
          	int c = in.get();
          	
          	while(c!=EOF)
          	{
          		arrayOfInts[c]++;
          		c = in.get();
          	}
          
          	int count = 0;
          	
          	cout<<"\nThe character frequencies are: \n\n";
          	while(count < 257)
          	{
          		while(arrayOfInts[count]!=0)
          		{
          			if(count == 10)
          			{
          				cout<<"\\n "<<arrayOfInts[count]<<"\n";
          				count++;
          			}
          			else 
          			{
          				cout<<char(count)<< " "<<arrayOfInts[count]<<"\n";
          				count++;
          			}
          		}
          		
          		count++;
          		
          	}
          	
          	in.close();
          
          	return arrayOfInts;
          
          	
          }
          It prints the character frequencies, then a segmentation fault. The array should be 256 characters to hold each printable character. Any ideas?
          Last edited by Frinavale; Dec 9 '09, 10:05 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            I'm sorry if I came across a bit strong yesterday. I was seeing a lot of threads where people would just post a bunch of code and title the thread "what's wrong with this code". Needless to say that I was pretty frustrated by the time I came across yours.

            I'm glad that you were able to narrow it down a bit for us.
            I think that the problem is occurring within this loop:
            Code:
            while(c!=EOF)
            {
                     arrayOfInts[c]++;
                     c = in.get();
            }
            You should check to make sure that "c" is a valid index before you do what you're doing.

            Try the following:
            Code:
            while(c!=EOF)
            { if(c>=0 && c<=256)
              {     
                arrayOfInts[c]++;
              }
                c = in.get();
            }
            -Frinny

            Comment

            • Frinavale
              Recognized Expert Expert
              • Oct 2006
              • 9749

              #7
              Um I take it back. It might be the loop that prints the values.

              What are you doing in the loop that prints the values!
              Why don't you just use for( count=0; count<=256; count++)???

              Comment

              • nar0122
                New Member
                • Nov 2009
                • 11

                #8
                I did. I changed it to a for loop and changed the other thing you suggested and I am still hitting a segmentation fault. Here is what I have now for reference.
                Code:
                int* getFrequency(char* filename, int arrayOfInts[])
                {
                	ifstream in;
                	in.open(filename);
                	for(int i = 0; i < 256; i++)
                	{
                		arrayOfInts[i] = 0;
                	}
                
                
                	
                	int c = in.get();
                	
                	while(c!=EOF)
                	{
                		if(c>0 && c<=256)
                		{
                			arrayOfInts[c]++;
                		}
                			c = in.get();
                	}
                
                	
                	
                	cout<<"\nThe character frequencies are: \n\n";
                	for(int count = 0; count<=256; count++)
                	{
                		while(arrayOfInts[count]!=0)
                		{
                			if(count == 10)
                			{
                				cout<<"\\n "<<arrayOfInts[count]<<"\n";
                				count++;
                			}
                			else 
                			{
                				cout<<char(count)<< " "<<arrayOfInts[count]<<"\n";
                				count++;
                			}
                		}
                		cout<<count<<"\n";
                		count++;
                		
                	}
                	
                	in.close();
                
                	return arrayOfInts;
                
                	
                }
                Last edited by Frinavale; Dec 10 '09, 02:05 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

                Comment

                • anhpnt
                  New Member
                  • Dec 2009
                  • 5

                  #9
                  Because your array has only 255 elements, the max index is 254. So the loop must be like this
                  Code:
                  for(int count = 0; count <= 254; count++)
                  or

                  Code:
                  for(int count = 0; count != 255; count++)
                  You get segmentation fault when you access the element that is not in array

                  Comment

                  • nar0122
                    New Member
                    • Nov 2009
                    • 11

                    #10
                    Which loop do I need that for in the above function? All of them? I tried changing all of the conditions for the loops like you said and I am still receiving the segmentation fault.

                    Comment

                    • anhpnt
                      New Member
                      • Dec 2009
                      • 5

                      #11
                      Could you debug this and show me the line where the program stopped?

                      Comment

                      • nar0122
                        New Member
                        • Nov 2009
                        • 11

                        #12
                        Yes, will do it now.

                        Comment

                        • nar0122
                          New Member
                          • Nov 2009
                          • 11

                          #13
                          This is my current code
                          See attached for output
                          It is doing exactly what I want, just printing the segmentation fault at the end. It is not getting to any other functions before or after it because of the segmentation fault

                          Code:
                          /*****************************************************************
                          *                            getFrequency                        *
                          ******************************************************************
                          * getFrequency takes an array of 256 integers.  It opens a       *
                          * file and counts the amount of character                        *
                          * frequencies that occur, storing that count into the position   *
                          * in the array that correpsonds with the character's             *
                          * Ascii value.                                                   *
                          *                                                                *
                          * For example, if the file reads "AAb" it stores the number 2 in *
                          * position 64 in the array since capital A is a 65 on the Ascii  *
                          * chart and arrays are zero based.                               *
                          *****************************************************************/
                          
                          int* getFrequency(char* filename, int arrayOfInts[])
                          {
                          	ifstream in;
                          	in.open(filename);
                          	for(int i = 0; i <= 256; i++)
                          	{
                          		arrayOfInts[i] = 0;
                          	}
                          
                          	int c = in.get();	
                          	while(c!=EOF)
                          	{		
                          			arrayOfInts[c]++;
                          			c = in.get();
                          	}
                          
                          	cout<<"\nThe character frequencies are: \n\n";
                          	for(int count = 0; count<=256; count++)
                          	{
                          		while(arrayOfInts[count]!=0)
                          		{
                          			if(count == 10)
                          			{
                          				cout<<"\\n "<<arrayOfInts[count]<<"\n";
                          				count++;
                          			}
                          			else 
                          			{
                          				cout<<char(count)<< " "<<arrayOfInts[count]<<"\n";
                          				count++;
                          			}
                          		}
                          	
                          	}
                          	
                          	in.close();
                          
                          	return arrayOfInts;
                          
                          	
                          }
                          Attached Files
                          Last edited by Frinavale; Dec 10 '09, 02:07 PM. Reason: Please do not post in all caps. Please post code in [code] ... [/code] tags. Added code tags and fixed all caps

                          Comment

                          • anhpnt
                            New Member
                            • Dec 2009
                            • 5

                            #14
                            The image is too small to see. Actually, even if i can see it clearly, i can't tell you what the error is, because there is not enough information.
                            According to your code, i saw that the upper bound of loop is 256, while the array size is 256. Correct it to 255.
                            Also, change the print loop as the following code, run it and show me last output lines (3 lines at most).

                            Code:
                            cout<<"\nThe character frequencies are: \n\n";
                            for(int count = 0; count<=255; count++)
                            {
                            cout << count << " ";
                            if (count == 10)
                                cout << "\\n ";
                            else
                                cout << char(count) << " ";
                            
                            cout << arrayOfInts[count]<<"\n";
                            }

                            Comment

                            • nar0122
                              New Member
                              • Nov 2009
                              • 11

                              #15
                              The last three lines are as follows:

                              254 \ufffd 0
                              255 \ufffd 0
                              Segmentation fault
                              nar0122@tecs-cs-sshpol3:~/Desktop/3300/assn4/programOne>

                              Comment

                              Working...