Thread: Unsolved Segmentation Fault

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    10

    Unsolved Segmentation Fault

    So, I'm getting a segmentation fault I can't solve. I have this code, with print statements to show where the program quits.
    Code:
    i = 0;
    	while(i<2000){
    		printf("Host name %s : %i \n i is %i\n", hostCon[i].hostName, hostCon[i].freq, i);
    		fprintf(host_freq, "%i\n", hostCon[i].freq);
    		printf("hi1\n");
    		fprintf(host_name, "%s", hostCon[i].hostName);
    		printf("hi2\n");
    		i++;
    		}
    	printf("out of for loop");
    And the print looks like this:

    Host name *******.com
    : 1
    i is 1999
    hi1
    hi2
    Segmentation fault


    It seems odd to me, because after the "hi2" the while loop should be finished, thus the next print statement should I appear. I don't understand how this segmentation fault occurs when there is nothing in between the two print statements. Let me know if more code is necessary to debug this. Thanks in advance.

  2. #2
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Seg fault is usually when you try to access memory that is out of bounds. Most commonly happens when you try to access an array past it's limit. My guess would be your while loop isn't terminating when you think it does. Hard to tell without more code.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    What have you done to debug the code and narrow it down to the block that maybe causing the segfault.

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    There is nothing fatally wrong with that piece of code. Show more related code (definitions / allocations etc).
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    10
    The print statements were added to see where the seg fault is. I'm having trouble with it, because the statements prints to show that i= 1999, which means it should quit the while loop after it is incremented and continue to the next print statement. I understand a seg fault has to do with accessing memory, but in this case there isn't any array or pointer that would cause a normal seg fault in between the "hi2" and "out of loop" print statements. Here is more code if it helps:

    Code:
    void sort(struct hostfreq hostCon[2001]){
    	FILE *host_freq;
        host_freq= fopen("hostfreq.txt", "a");
        FILE *host_name;
        host_name= fopen("hostname.txt", "a");
    	//printf("in sort\n");
    	struct hostfreq temp[1];
    	//printf("defined temp\n");
    	int i, j = 0;
    	for(i; i<=1999; i++){
    		j=i+1;
    		for(j; j<=1999;j++){
    				if(hostCon[j].freq>hostCon[i].freq){
    					temp[0] = hostCon[j];
    					hostCon[j] = hostCon[i];
    					hostCon[i]=temp[0];
    				}
    		}
    	}
    	i = 0;
    	while(i<2000){
    		printf("Host name %s : %i \n i is %i\n", hostCon[i].hostName, hostCon[i].freq, i);
    		fprintf(host_freq, "%i\n", hostCon[i].freq);
    		printf("hi1\n");
    		fprintf(host_name, "%s", hostCon[i].hostName);
    		printf("hi2\n");
    		i++;
    		}
    	printf("out of for loop");
    	fclose(host_freq);
    	fclose(host_name);
    	int total = sum(hostCon);
    	printf("sort done");
    	CDF(hostCon, total);
    }

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Using printf to debug is prone to the following error: stdout is buffered, meaning you could have this:

    Code:
    printf("Everything okay");
    [...]
    [some line causing segfault]
    But when you run it, the message is still in the stdout buffer at the crash, making you believe that the printf line has not been executed yet when actually it has. So either:

    Code:
    printf("Everything okay"); 
    fflush(stdout);
    // or
    fprintf(stderr, "Everything okay");
    Since stderr is not buffered.

    By far the easiest way to locate a segfault is in a real debugger, which evidently you do not use, but from the look of your code, you are at a point where you do need to learn to ASAP. Let us know what OS you are using and someone can get you started in the right direction.

    Otherwise it's hard to say. Eg, you use fopen() without checking for errors, and using a bad handle will cause a segfault. Etc.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Variable i is being used without being initialized.
    Code:
    for(i; i<=1999; i++){
    It's probably some out-of-bounds garbage.

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Also there's no check to see if the files actually opened or not...

  9. #9
    Registered User
    Join Date
    Jun 2011
    Posts
    10
    MK27, thanks for the advice with using printf.
    My trouble is the past 3 years I've been programming in Java and for my current research they asked me to change to C, because it needs to be lower level coding. I'm used to using IDEs, but haven't made the move to one for C yet. Segmentation faults seem to be my nemesis since I started 3 weeks ago. I'm running Ubuntu and coding in Gedit. Is there a debugging plugin of some sort? I'd prefer to stay with a very simple program still, last time I coded in C or C++ was 3 years ago and it was on Microsoft Visual studio, which was the biggest headache ever. I used eclipse for java, but it still wasn't my favorite. If someone can still spot the seg fault above, it would be much appreciated though.

    nonoob, I believe i is initialized the line above "int i, j = 0"

  10. #10
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    No it isn't. Just j is initialized by that line. You need to do int i = 0, j = 0

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by uconnhuskies View Post
    nonoob, I believe i is initialized the line above "int i, j = 0"
    Actually with that code, j is initialized to 0 but i is not initialized at all and might contain any random value.

  12. #12
    Registered User
    Join Date
    Jun 2011
    Posts
    10
    My fault, I changed it to initialize i also. Thanks.

    To check if a file is open do I just check that the stream is not equal to NULL?

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by uconnhuskies View Post
    To check if a file is open do I just check that the stream is not equal to NULL?
    Yep.
    Code:
    fp = fopen( ... )
    if( fp == NULL )
        ...boo...
    else
        ...yay...

    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Check the man pages:
    Quote Originally Posted by man fopen
    RETURN VALUE
    Upon successful completion fopen(), fdopen() and freopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

  15. #15
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by uconnhuskies View Post
    My fault, I changed it to initialize i also. Thanks.

    To check if a file is open do I just check that the stream is not equal to NULL?
    Yep... like this...

    Code:
    FILE *host_freq;
    host_freq= fopen("hostfreq.txt", "a");
    
    if (! host_freq)
     { printf("Host Frequency file not opened!")
        exit(1); }
    Obviously you don't want to continue processing if the files are not correctly opened.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault
    By ankitsinghal_89 in forum C Programming
    Replies: 2
    Last Post: 06-28-2010, 01:45 AM
  2. Segmentation Fault
    By lombardom in forum C Programming
    Replies: 8
    Last Post: 06-06-2010, 03:17 PM
  3. Interview question unsolved for long time...Plz help
    By kush.asthana in forum C++ Programming
    Replies: 2
    Last Post: 01-30-2008, 12:48 AM
  4. Segmentation Fault Again
    By mrbump2004 in forum C Programming
    Replies: 6
    Last Post: 12-05-2004, 02:31 PM
  5. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM

Tags for this Thread