473,499 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why am i getting a segmentation fault in my output?

11 New Member
Expand|Select|Wrap|Line Numbers
  1. //Nicholas Riseden
  2. //CSCI 3300
  3. //Assignment 4 Version 2
  4.  
  5. #include "tree.h"
  6. #include "pqueue.h"
  7. #include <string>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <stdio.h>
  11. #include "binary1.h"
  12.  
  13. using namespace std;
  14.  
  15. /*****************************************************************
  16. *                            buildTree                           *
  17. ******************************************************************
  18. * buildTree takes the array built from getFrequency and builds a *
  19. * tree that holds a character and its priority using the insert  *
  20. * function.                                                      *
  21. *                                                                *
  22. * For example, if the file reads "AAb" it creates a node for the *
  23. * character 'A' and stores its priority 2 for that node.         *
  24. *****************************************************************/
  25. Node* buildTree(int arrayOfInts[])
  26. {
  27.     PriorityQueue q;
  28.     for(int x = 0; x <= 255; x++)
  29.     {
  30.         if(arrayOfInts[x]!=0)
  31.         {            
  32.             Node* leaf = new Node((char)x);
  33.             insert(q, leaf, arrayOfInts[x]);
  34.         }
  35.     }
  36.  
  37.     Node* t1,*t2;
  38.     int p1, p2;
  39.     remove(q, t1, p1);
  40.  
  41.     while(isEmpty(q)==false)
  42.     {
  43.         remove(q,t2, p2);
  44.         Node* t3 = new Node(t1, t2);
  45.         insert(q, t3, (p1 +p2));
  46.         remove(q, t1, p1);
  47.     }
  48.  
  49.     return t1;
  50. }
  51.  
  52. /*****************************************************************
  53. *                            getFrequency                        *
  54. ******************************************************************
  55. * getFrequency takes an array of 256 integers.  It opens a       *
  56. * file and counts the amount of character                        *
  57. * frequencies that occur, storing that count into the position   *
  58. * in the array that correpsonds with the character's             *
  59. * Ascii value.                                                   *
  60. *                                                                *
  61. * For example, if the file reads "AAb" it stores the number 2 in *
  62. * position 64 in the array since capital A is a 65 on the Ascii  *
  63. * chart and arrays are zero based.                               *
  64. *****************************************************************/
  65.  
  66. int* getFrequency(char* filename, int arrayOfInts[])
  67. {
  68.     ifstream in;
  69.     in.open(filename);
  70.     for(int i = 0; i < 256; i++)
  71.     {
  72.         arrayOfInts[i] = 0;
  73.     }
  74.  
  75.  
  76.  
  77.     int c = in.get();
  78.  
  79.     while(c!=EOF)
  80.     {
  81.         arrayOfInts[c]++;
  82.         c = in.get();
  83.     }
  84.  
  85.     int count = 0;
  86.     cout<<"\nThe character frequencies are: \n\n";
  87.     int k = 0;
  88.     while(k < 256)
  89.     {
  90.  
  91.         if(k>0)
  92.         {
  93.  
  94.             if(k == 10)
  95.             {
  96.                 cout<<"\\n "<<arrayOfInts[k]<<"\n";
  97.             }
  98.             else if(k!=10)
  99.             {
  100.             cout<<char(k)<< " "<<arrayOfInts[k]<<"\n";
  101.             }
  102.         }
  103.  
  104.  
  105.     count++;
  106.     cout<<"count is "<<count<<"\n";//count reaches 256, then segmentation fault is printed
  107.     k++;
  108.     }
  109.  
  110.     in.close();
  111.     cout<<"This is sparta\n";
  112.     return arrayOfInts;
  113.     cout<< "This is over\n";
  114.  
  115. }
  116.  
  117. //comments to describe this function
  118. void writeTree(BFILE* f, Node* t)
  119. {  
  120.         if(t->kind!=leaf)
  121.         {
  122.             writeBit(f, 0);
  123.             writeTree(f, t->left);
  124.             writeTree(f, t->right);
  125.         }
  126.         else
  127.         {
  128.             writeBit(f, 1);
  129.             writeByte(f, t->ch);
  130.         }
  131.  
  132.  
  133. }
  134. //buildcode
  135. void buildCode(Node* n, string codeArray[], string pref)
  136. {
  137.     if(n->kind == leaf)
  138.     {    
  139.         codeArray[int(n->ch)] = pref;
  140.     }
  141.     else if(n->kind == nonleaf)
  142.     {
  143.         buildCode(n->left, codeArray, pref + "0");
  144.         buildCode(n->right, codeArray, pref + "1");
  145.     }
  146.  
  147. }
  148. //writecode(f, str) writes string str to BFILE* f, one bit
  149. //at a time.
  150. void writeCode(BFILE* f, string str)
  151. {
  152.         int y = str.length();
  153.         for(int x = 0; x < y; x++)
  154.         {
  155.             writeBit(f, str[x]);
  156.         }
  157.  
  158. }
  159.  
  160. //function description
  161. void writeCodedFile(char* filename, string codearray[], BFILE* f)
  162. {
  163.     ifstream in;
  164.     in.open(filename);
  165.         int c = cin.get();
  166.         while(c != EOF)
  167.         {
  168.             writeCode(f, codearray[c]);
  169.             c = cin.get();
  170.         }
  171. cout<<"Test E";
  172.     in.close();
  173. }
  174.  
  175.  
  176. int main(int argc, char* argv[])
  177. {
  178.         string codeArray[255];
  179.     int arrayOfInts[255];
  180.     int* frequencyArray = getFrequency(argv[1], arrayOfInts);//problem is here
  181.     cout<<"I am about to do buildTree.";//this never gets printed
  182.     Node* n = buildTree(frequencyArray);
  183.     cout<<"I am done buildTree.";//this never gets printed
  184.     buildCode(n, codeArray, "");
  185.  
  186.     BFILE* f = openBinaryFileWrite(argv[2]);
  187.  
  188.     writeTree(f,n);
  189.  
  190.     writeCodedFile(argv[1], codeArray,f);
  191.  
  192.     closeBinaryFileWrite(f);
  193.  
  194.     return 0;
  195.  
  196. }
Dec 8 '09 #1
18 2959
Frinavale
9,735 Recognized Expert Moderator Expert
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
Dec 8 '09 #2
Airslash
221 New Member
never mind my post, reshifted your code and my comment was incorrect.
Try providing the error message and line number if possible, helps alot
Dec 8 '09 #3
jfwfmt
11 New Member
check on whether char is signed or unsigned by default

/s/ Jim WIlliams
Dec 9 '09 #4
nar0122
11 New Member
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.
Expand|Select|Wrap|Line Numbers
  1. /*****************************************************************
  2. *                            getFrequency                        *
  3. ******************************************************************
  4. * getFrequency takes an array of 256 integers.  It opens a       *
  5. * file and counts the amount of character                        *
  6. * frequencies that occur, storing that count into the position   *
  7. * in the array that correpsonds with the character's             *
  8. * Ascii value.                                                   *
  9. *                                                                *
  10. * For example, if the file reads "AAb" it stores the number 2 in *
  11. * position 64 in the array since capital A is a 65 on the Ascii  *
  12. * chart and arrays are zero based.                               *
  13. *****************************************************************/
  14.  
  15. int* getFrequency(char* filename, int arrayOfInts[])
  16. {
  17.     ifstream in;
  18.     in.open(filename);
  19.     for(int i = 0; i < 257; i++)
  20.     {
  21.         arrayOfInts[i] = 0;
  22.     }
  23.  
  24.  
  25.  
  26.     int c = in.get();
  27.  
  28.     while(c!=EOF)
  29.     {
  30.         arrayOfInts[c]++;
  31.         c = in.get();
  32.     }
  33.  
  34.     int count = 0;
  35.  
  36.     cout<<"\nThe character frequencies are: \n\n";
  37.     while(count < 257)
  38.     {
  39.         while(arrayOfInts[count]!=0)
  40.         {
  41.             if(count == 10)
  42.             {
  43.                 cout<<"\\n "<<arrayOfInts[count]<<"\n";
  44.                 count++;
  45.             }
  46.             else 
  47.             {
  48.                 cout<<char(count)<< " "<<arrayOfInts[count]<<"\n";
  49.                 count++;
  50.             }
  51.         }
  52.  
  53.         count++;
  54.  
  55.     }
  56.  
  57.     in.close();
  58.  
  59.     return arrayOfInts;
  60.  
  61.  
  62. }
It prints the character frequencies, then a segmentation fault. The array should be 256 characters to hold each printable character. Any ideas?
Dec 9 '09 #5
Frinavale
9,735 Recognized Expert Moderator Expert
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:
Expand|Select|Wrap|Line Numbers
  1. while(c!=EOF)
  2. {
  3.          arrayOfInts[c]++;
  4.          c = in.get();
  5. }
You should check to make sure that "c" is a valid index before you do what you're doing.

Try the following:
Expand|Select|Wrap|Line Numbers
  1. while(c!=EOF)
  2. { if(c>=0 && c<=256)
  3.   {     
  4.     arrayOfInts[c]++;
  5.   }
  6.     c = in.get();
  7. }
-Frinny
Dec 9 '09 #6
Frinavale
9,735 Recognized Expert Moderator Expert
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++)???
Dec 9 '09 #7
nar0122
11 New Member
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.
Expand|Select|Wrap|Line Numbers
  1. int* getFrequency(char* filename, int arrayOfInts[])
  2. {
  3.     ifstream in;
  4.     in.open(filename);
  5.     for(int i = 0; i < 256; i++)
  6.     {
  7.         arrayOfInts[i] = 0;
  8.     }
  9.  
  10.  
  11.  
  12.     int c = in.get();
  13.  
  14.     while(c!=EOF)
  15.     {
  16.         if(c>0 && c<=256)
  17.         {
  18.             arrayOfInts[c]++;
  19.         }
  20.             c = in.get();
  21.     }
  22.  
  23.  
  24.  
  25.     cout<<"\nThe character frequencies are: \n\n";
  26.     for(int count = 0; count<=256; count++)
  27.     {
  28.         while(arrayOfInts[count]!=0)
  29.         {
  30.             if(count == 10)
  31.             {
  32.                 cout<<"\\n "<<arrayOfInts[count]<<"\n";
  33.                 count++;
  34.             }
  35.             else 
  36.             {
  37.                 cout<<char(count)<< " "<<arrayOfInts[count]<<"\n";
  38.                 count++;
  39.             }
  40.         }
  41.         cout<<count<<"\n";
  42.         count++;
  43.  
  44.     }
  45.  
  46.     in.close();
  47.  
  48.     return arrayOfInts;
  49.  
  50.  
  51. }
Dec 9 '09 #8
anhpnt
5 New Member
Because your array has only 255 elements, the max index is 254. So the loop must be like this
Expand|Select|Wrap|Line Numbers
  1. for(int count = 0; count <= 254; count++)
or

Expand|Select|Wrap|Line Numbers
  1. for(int count = 0; count != 255; count++)
You get segmentation fault when you access the element that is not in array
Dec 10 '09 #9
nar0122
11 New Member
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.
Dec 10 '09 #10
anhpnt
5 New Member
Could you debug this and show me the line where the program stopped?
Dec 10 '09 #11
nar0122
11 New Member
Yes, will do it now.
Dec 10 '09 #12
nar0122
11 New Member
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

Expand|Select|Wrap|Line Numbers
  1.  
  2. /*****************************************************************
  3. *                            getFrequency                        *
  4. ******************************************************************
  5. * getFrequency takes an array of 256 integers.  It opens a       *
  6. * file and counts the amount of character                        *
  7. * frequencies that occur, storing that count into the position   *
  8. * in the array that correpsonds with the character's             *
  9. * Ascii value.                                                   *
  10. *                                                                *
  11. * For example, if the file reads "AAb" it stores the number 2 in *
  12. * position 64 in the array since capital A is a 65 on the Ascii  *
  13. * chart and arrays are zero based.                               *
  14. *****************************************************************/
  15.  
  16. int* getFrequency(char* filename, int arrayOfInts[])
  17. {
  18.     ifstream in;
  19.     in.open(filename);
  20.     for(int i = 0; i <= 256; i++)
  21.     {
  22.         arrayOfInts[i] = 0;
  23.     }
  24.  
  25.     int c = in.get();    
  26.     while(c!=EOF)
  27.     {        
  28.             arrayOfInts[c]++;
  29.             c = in.get();
  30.     }
  31.  
  32.     cout<<"\nThe character frequencies are: \n\n";
  33.     for(int count = 0; count<=256; count++)
  34.     {
  35.         while(arrayOfInts[count]!=0)
  36.         {
  37.             if(count == 10)
  38.             {
  39.                 cout<<"\\n "<<arrayOfInts[count]<<"\n";
  40.                 count++;
  41.             }
  42.             else 
  43.             {
  44.                 cout<<char(count)<< " "<<arrayOfInts[count]<<"\n";
  45.                 count++;
  46.             }
  47.         }
  48.  
  49.     }
  50.  
  51.     in.close();
  52.  
  53.     return arrayOfInts;
  54.  
  55.  
  56. }
Attached Images
File Type: jpg segmentationfault.jpg (9.3 KB, 226 views)
Dec 10 '09 #13
anhpnt
5 New Member
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).

Expand|Select|Wrap|Line Numbers
  1. cout<<"\nThe character frequencies are: \n\n";
  2. for(int count = 0; count<=255; count++)
  3. {
  4. cout << count << " ";
  5. if (count == 10)
  6.     cout << "\\n ";
  7. else
  8.     cout << char(count) << " ";
  9.  
  10. cout << arrayOfInts[count]<<"\n";
  11. }
  12.  
Dec 10 '09 #14
nar0122
11 New Member
The last three lines are as follows:

254 \ufffd 0
255 \ufffd 0
Segmentation fault
nar0122@tecs-cs-sshpol3:~/Desktop/3300/assn4/programOne>
Dec 10 '09 #15
anhpnt
5 New Member
I have run your code successfully, and the output is different from yours.
I guess the error is somewhere outside this function.
Also, could you send me you input file?
You should use debugging tools to find the error more easily.
Dec 10 '09 #16
Frinavale
9,735 Recognized Expert Moderator Expert
I see what you're doing now.
You're trying to do too much with one variable.

You need one variable to keep track of how many times you have iterated through the array (how many times you've looped).

You should be using another variable to print the number of characters found in the array at that iteration.

If there is 0 for a specific character then don't do anything ...just loop to the next index.

This is a much cleaner approach that I hope will fix your problem.
Expand|Select|Wrap|Line Numbers
  1. int* getFrequency(char* filename, int arrayOfInts[])
  2. {  
  3.     ifstream in;
  4.     for(int i = 0; i < 256; i++)
  5.     {
  6.         arrayOfInts[i] = 0;
  7.     }  
  8.  
  9.     in.open(filename);
  10.     int c = in.get();    
  11.      while(c!=EOF)
  12.     {
  13.         if(c>0 && c<256)
  14.         {
  15.             arrayOfInts[c]++;
  16.         }
  17.         c = in.get();
  18.     }
  19.     in.close();
  20.  
  21.     cout<<"\nThe character frequencies are: \n\n";
  22.     int numberOfCharacters = 0;
  23.     for(int i = 0; i<256; i++)
  24.     {   numberOfCharacters = arrayOfInts[i];
  25.         if(i==10}
  26.         {   cout << "\\n ";}
  27.         if(numberOfCharacters > 0)
  28.         {
  29.                 cout<<char(i)<< " "<<numberOfCharacters<<"\n";
  30.         }
  31.     }
  32.  
  33.     return arrayOfInts;  
  34. }
-Frinny

PS. Could you please post code snippets in code tags.
Dec 10 '09 #17
nar0122
11 New Member
I did not get the segmentation fault after modifying my program; however, I got some pretty crazy errors. I think it is saying I have a memory leak somewhere.

Does this mean anything to anyone?

*** glibc detected *** ./huffman: free(): invalid pointer: 0x00007fffd55926f8 ***
Dec 10 '09 #18
Frinavale
9,735 Recognized Expert Moderator Expert
Nar0122, does that mean your original problem is fixed?
If so, please start a new thread for your new problem and indicate which post helped you to solve the problem you needed help with in this thread.

-Frinny
Dec 10 '09 #19

Sign in to post your reply or Sign up for a free account.

Similar topics

6
4745
by: Jay donnell | last post by:
I have a short multi-threaded script that checks web images to make sure they are still there. I get a segmentation fault everytime I run it and I can't figure out why. Writing threaded scripts is...
9
3153
by: fudmore | last post by:
Hello Everybody. I have a Segmentation fault problem. The code section at the bottom keeps throwing a Segmentation fault when it enters the IF block for the second time. const int...
11
4702
by: Polar | last post by:
Hi! i'm a newbie in C language and i'm writing my first simple codes. In one of these, my purpose is to append the ascii value of an interger (example 101 --> e) at the end of a string to...
6
2288
by: damian birchler | last post by:
If I run the following I get a segmentation fault: #define NAMELEN 15 #define NPERS 10 typedef struct pers { char name; int money; } pers_t;
6
4736
by: I_have_nothing | last post by:
Hi! I am new in C. I try to use dynamical allocation fuction malloc( ) and realloc( ). I found something strange. After several calling realloc( ), the malloc( ) will give me a Segmentation...
5
2974
by: Fra-it | last post by:
Hi everybody, I'm trying to make the following code running properly, but I can't get rid of the "SEGMENTATION FAULT" error message when executing. Reading some messages posted earlier, I...
27
3314
by: Paminu | last post by:
I have a wierd problem. In my main function I print "test" as the first thing. But if I run the call to node_alloc AFTER the printf call I get a segmentation fault and test is not printed! ...
7
5856
by: pycraze | last post by:
I would like to ask a question. How do one handle the exception due to Segmentation fault due to Python ? Our bit operations and arithmetic manipulations are written in C and to some of our...
3
5128
by: madunix | last post by:
My Server is suffering bad lag (High Utlization) I am running on that server Oracle10g with apache_1.3.35/ php-4.4.2 Web visitors retrieve data from the web by php calls through oci cobnnection...
6
5019
by: DanielJohnson | last post by:
int main() { printf("\n Hello World"); main; return 0; } This program terminate just after one loop while the second program goes on infinitely untill segmentation fault (core dumped) on...
0
7009
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7178
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7223
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6899
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7390
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4919
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3103
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1427
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.