Thread: Segmentation Fault

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    208

    Segmentation Fault

    I cannot seem to figure out where I am getting a segmentation fault in my program. I've narrowed it down to where it is occurring but everything seems ok to me.

    Code:
    void nearest_neighbor(int s){
    	
    	int k = 0, i = 0, count = 0; // loop counters
    	int bin = 0.0;   // A temp. variable to use to bin r's
    	float rx = 0.0 , r1, r2;
    	float ry = 0.0;
    	float rz = 0.0;
    	float rA[NUM_A], rB[NUM_B], rAN[NUM_A], rBN[NUM_B];
    	float dr = Lx/2.0/Nbins;
    	
    	/*******************   AA Histogram Calculation  **************************************/	
    	for(k = 0; k < NUM_A; k++){
    		
    		// sit on one particle and calculate/store all distances between all pairs
    		for(i = 0; i < NUM_A; i++){  
    			
    			if (k == i){ i++; }         // skip the case when i = k because it will always be 0.0
    			
    			rx = (x[k] - x[i])- Lx*rintl((x[k] - x[i])/Lx);
    			ry = (y[k] - y[i])- Ly*rintl((y[k] - y[i])/Ly);
    			rz = (z[k] - z[i])- Lz*rintl((z[k] - z[i])/Lz);
    			
    			rA[i] = sqrt(rx*rx*+ry*ry+rz*rz);
    			
    		}
    		
    		quickSort(rA, NUM_A);  // sort the distances between pairs
    		rAN[k] = rA[s];
    		
    	}
    	
    		
    		for (i = 0; i < Nbins; i++){
    			
    			r1 = i*dr;
    			r2 = r1 + dr;
    			
    			for (count = 0; count < NUM_A; count++){ 
    				if (rAN[count] < r2 && rAN[count] >= r1){
    					histAA[i]++;
    				} 
    			}
    		}
    	
    	
    	/***************************************************************************************************************/	
    }
    I'm pretty sure it is happening during the last nested loop of the function. FYI histAA[] has Nbins elements and is defined globally.

    Any help would be huge.

    Thanks!
    Paddon
    Jeff Paddon
    Undergraduate Research Assistant
    Physics Department
    St. Francis Xavier University

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So when k is the last element, your last turn in the i-loop will then go out of bounds, as you add an extra one to i. (If you want to skip processing, just use continue.)

  3. #3
    Registered User
    Join Date
    Jun 2009
    Posts
    486
    Code:
    		for(i = 0; i < NUM_A; i++){  
    			
    			if (k == i){ i++; }
    should be

    Code:
    		for(i = 0; i < NUM_A; i++){  
    			
    			if (k == i){continue; }
    you were double incrementing on the steps you skip and it was putting the index out of bounds on the last run through the loops
    Last edited by KBriggs; 06-10-2009 at 10:35 AM.

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by kas2002 View Post
    I cannot seem to figure out where I am getting a segmentation fault in my program. I've narrowed it down to where it is occurring but everything seems ok to me.

    I'm pretty sure it is happening during the last nested loop of the function.
    Place this
    Code:
    printf("DEBUG!\n");fflush(stdout);
    before a line where you think the seg fault occurs. The fflush() part is important.

    If it prints out, keep moving it down one line at a time until it does not appear before the fault happens. That is *exactly* where your error occured -- altho the real cause may still be more complex, this will be your best clue.
    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

  5. #5
    Registered User
    Join Date
    May 2002
    Posts
    208
    Cool MK27 thanks for the tip, I was having difficultly locking down where exactly it was happening because of the fact that.

    Cool, I see it now. I was looking in the complete wrong place for the seg fault.

    Thanks!
    Jeff Paddon
    Undergraduate Research Assistant
    Physics Department
    St. Francis Xavier University

  6. #6
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Iterating over all pairs, when order does not matter, always look like this:

    Code:
    for(i = 0; i < N - 1; ++i)
    {
        for(j = i + 1; j < N; ++j)
        {
            ...
        }
    }
    Iterating over all pairs when order matters looks like this:

    Code:
    for(i = 0; i < N; ++i)
    {
        for(j = 0; j < N; ++j)
        {
            if(i != j)
            {
                ...
            }
        }
    }
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Better to run it in the debugger.

    It will then point you at the exact line which causes the segfault, AND give you the chance to print out variables etc to see which subscript is stepping past the end of which array, or which pointer is either NULL or garbage.

    Debugging by placing random printf's has limited usefulness.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Salem View Post
    AND give you the chance to print out variables etc to see which subscript is stepping past the end of which array, or which pointer is either NULL or garbage.
    Debugging by placing random printf's has limited usefulness.
    It is not a big step to go:
    Code:
    printf("%?\n", somevar);fflush(stdout);
    if you want to do stuff like "check a variable for garbage", etc. In fact, it is even more helpful, since printf will spring it's own errors for certain variable related mistakes, and cause a fault on others*.

    My problem with gdb is that it will trace back into a library, which is totally unhelpful if you are not trying to debug the library. With large, complicated API's it is rendered useless. I used gdb a lot when I first started with C, writing 20-50 lines of code. Then I got into gtk+, and gdb proved to be a complete waste of time compared to the simple printf. I tried gdb so many times, secondarily resorting to printf, that I finally decided it made more sense the other way around -- use printf first, then if you are still confused, use printf and gdb. Unless you are tired of using your fingers and keyboard, in which case it makes sense to want to point and click at things

    I am sure using a debugger is an acquired skill one must learn, but I would say the same thing about skilful use of the printf.

    * in which case gdb will point to the printf.
    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

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by MK27
    if you want to do stuff like "check a variable for garbage", etc. In fact, it is even more helpful, since printf will spring it's own errors for certain variable related mistakes, and cause a fault on others*.
    That sounds more like a job for an assertion instead of a printf call that will be removed shortly.

    Quote Originally Posted by MK27
    My problem with gdb is that it will trace back into a library, which is totally unhelpful if you are not trying to debug the library. With large, complicated API's it is rendered useless.
    Perhaps it is just a problem with your use of gdb? It seems to me that you should be able to avoid this.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by laserlight View Post
    Perhaps it is just a problem with your use of gdb? It seems to me that you should be able to avoid this.
    Perhaps. It could be I don't use the tool right. When printf fails me, I will get more motivated that way.

    I'm not sure if I want to or even should *trust* these kinds of tools, which, for all I know, promote laziness and ineptitude. I ran into problems using valgrind on gtk+ stuff too, and when I googled around, I found out I was not the only one! This was so heated and contentious there were threads (more than one in different places, at different times) with professional programmers *demanding* that gtk 2.0 be re-written so that valgrind could analyse it better! Ie, valgrind was beyond reproach, and it was everything else that had to be adjusted so that (let's extend this philosophy) your debugger, IDE, etc, etc would once again be the prized piece of software you seem to believe it is.

    Just an opinion. Basically, I think if you program carefully and test enough printf will solve most of the remaining problems. Perhaps in time I will change that opinion...
    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

  11. #11
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    I'm not sure if I want to or even should *trust* these kinds of tools, which, for all I know, promote laziness and ineptitude
    Using gdb promotes laziness and ineptitude, but throwing in random print statements until you narrow down the line that causes the crash is ok? That sounds backwards to me.

  12. #12
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by MK27 View Post
    My problem with gdb is that it will trace back into a library, which is totally unhelpful if you are not trying to debug the library. With large, complicated API's it is rendered useless.
    In theory, gdb could skip the backtrace entries which come from other loaded modules (dynamic libraries), but I don't think it has that feature.

    For statically linked libraries, gdb obviously has no way of knowing which functions are yours and which are library functions. Unless you had a massive list of all "uninteresting" functions. Again, I don't think gdb has such a feature.

    I don't find it to be much of a problem, myself. If you name your functions consistently, perhaps by prefixing them all with a tag that indicates that they are "your" functions, you could visually filter on that.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > My problem with gdb is that it will trace back into a library
    Your point being it's too difficult to use the 'up' command to navigate to the stack frame of interest?

    > With large, complicated API's it is rendered useless
    WTF - are you gunning for the most bone-headed statement of the week award?

    > I tried gdb so many times
    Well the problem is, you never learnt how to use it properly BEFORE your programs became so big that a debugger was essential.
    So you resort to printf debugging.
    Don't spread your own mis-fortune on others as being "best advice".

    Unusual software bug - Wikipedia, the free encyclopedia
    Now, when adding your printf() makes the problem "GO AWAY", what on earth are you going to do then?
    Or worse, it crashes somewhere else instead.

    Or where it's taken you several hours of testing to get to the point of failure, and you want to debug. Just debug it already, don't spend more time recompiling the code with your "best guess" as to where the problem is, and then hours more testing to get back to the point of failure, only to find out you guessed wrong.

    Wait, there's more.
    With some debuggers, it's possible to do simple "repair and continue". The best your printf approach can offer is, "It's worse than that, it's dead Jim".

    > since printf will spring it's own errors for certain variable related mistakes,
    Fantastic - you replaced a trap in strcpy with a trap in printf - exactly how much further forward have you gotten. This is worth zilch IMO.

    Finally, when you've finished your Opus, you have to go through all the code taking them all out again so you can release it. Unless you were clever enough to make it so all your debug logging was conditionally compiled.

    > I'm not sure if I want to or even should *trust* these kinds of tools,
    Like your compiler, editor, OS, browser, etc etc?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    For starters, your thing about a "Heisenburg" bug would apply to something that faults under one compiler and not another, so your assertion that the debugger will help you with the bug you didn't know about is just stupid. The assertion that using printf will make this any more or less likely is a non-sequiter IMO. I certainly would not consider a problem solved just because it magically disappeared when I added an extra (debugging) line, if that's what you were thinking. I do not consider luck a method. The problem is not solved until I have and explanation as to why it happened.

    Vis, going "up" into the stack, I will keep that in mind for later. Usually, my problem with large API's is misuse of an unfamiliar command.

    I also work in more languages than just C, so it is nice not to be dependant on a method which requires more software which may not exist. They all seem to have a "print", tho.

    Quote Originally Posted by Salem View Post
    Unless you were clever enough to make it so all your debug logging was conditionally compiled.
    Of course! I even arrange them in levels and groups:
    Code:
    if (debug > 2) fprintf(log, "funcname:  [blah blah]
    Using debug statements that are more than just disposable is also great if someone else using your software has a problem. All I have to do is say, "Run it with --debug 3 and send me the output." This is not my own unique idea, of course, and it also helps to sort out usage problems that don't involve code bugs. Good thing I left all that printf in there....

    Fantastic - you replaced a trap in strcpy with a trap in printf - exactly how much further forward have you gotten. This is worth zilch IMO.
    There's another gross over simplification. Do you think I am that stupid? Or that I should believe *you* are the clever one? My point was more that this short circuits the library stack trace issue, because now the fault occurs *in* your code because of a dud pointer or whatever.

    And printf does not fault on a null pointer, whereas some commands do. Meaning, the only way to know it was null was via printf. I am sure you can do that with gdb too, it is just 10x more awkward.

    Quote Originally Posted by Salem View Post
    Like your compiler, editor, OS, browser, etc etc?
    Yes, I am happy all these things are *perfect* now.

    And let's not forget:
    Quote Originally Posted by kas2002 View Post
    Cool MK27 thanks for the tip, I was having difficultly locking down where exactly it was happening because of the fact that.

    Cool, I see it now. I was looking in the complete wrong place for the seg fault.

    Thanks!
    Of course, there is a counter-case for almost everything, but most likely this really did solve the problem.
    Last edited by MK27; 06-10-2009 at 01:22 PM.
    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

  15. #15
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Since this has ALREADY derailed into a "using a debugger makes you stupid" or some such, I thought I may add some of my experience.

    A debugger is a tool. Use it when it's right. A typical "right" time is when your code crashes in a loop that iterates through a bunch of array elements. Looking back on the stack to find out what the values are and finding out why it's crashes is easy.

    Even if it crashes inside some API that has a long call-stack, it is NORMALLY because your code passed some rubbish into a function, and by tracking back to YOUR code, it is possible to find out what went wrong there.

    GUI code can be a bit harder, because often the code of your own that runs is only peripheral (at the end of a long call-chain), and the call that CAUSED this call isn't anywhere on the call-stack. This can be both difficult and annoying to debug, and a debugger like GDB will probably not help much here. But unfortunately, calling a debugger useless simply because it can't deal with some particular scenario is unfair.

    There are times when you either can't use a debugger (there may not be a suitable way to make the bug appear in reasonable time, or the bug happens in some sort of real-time sensitive code [interrupt handler for example]) or there is no debugger available for the platform. In that case, there is no real option but to add some sort of tracing/logging - in the timing sensitive code, it's not even meaningful to use printfs, because it would be too slow - instead, you'd store information into some sort of buffer and then pull it out later on.

    I have probably spent more time in front of a debugger window than I have spent actually writing code - because when you get to LARGE code projects, often you track down bugs in some part of code that you have NO IDEA what it does, and it may be 15-20 calls from YOUR code to the actual place where it starts going wrong (but the failure happens when we've gone back up the stack 5-6 levels, and then back down another 5 calls, so you need to track down where things actually happened - and that can take days sometimes).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault problem
    By odedbobi in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2008, 03:36 AM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 05:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 12:53 PM