Thread: Segmentation fault - won't enter for loop!

  1. #16
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    I now see a way that it can seg-fault. It can happen if the program fails to open the output file.
    So, first thing I would do is add a null check before trying to printf into it.
    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"

  2. #17
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Calculation should use cast:
    x = (double)i/steps;
    Otherwise dividing an int with an int will not get desired result.

  3. #18
    Registered User
    Join Date
    Nov 2011
    Posts
    16
    Ha! it was all those for loops below. i had:

    Code:
    for(i=0; i++; i<10)
    Should have been:

    Code:
    for(i=0; i<10; i++)
    Stupid mistakes!

  4. #19
    Registered User
    Join Date
    Dec 2007
    Posts
    214
    A problem I see :

    Code:
    #define MAX_N 10
    
    double  integral_yn[MAX_N]
    
    for(n=1; n<10; n++)
    {  ....
    
       integral_yn[n] = 0;
    
    }
    your integral_yn has 10 members, 0 - 9. Your for loop uses indexes 1 - 10.

  5. #20
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by DaveH View Post
    A problem I see :

    Code:
    #define MAX_N 10
    
    double  integral_yn[MAX_N]
    
    for(n=1; n<10; n++)
    {  ....
    
       integral_yn[n] = 0;
    
    }
    your integral_yn has 10 members, 0 - 9. Your for loop uses indexes 1 - 10.
    Actually he's only using 9 of the 10 since he's starting at 1 ....

    Follow that loop around a few times...
    n = 1 ... n is < 10 ... assign value
    n = n + 1
    n = 2 ... n is < 10 ... assign value
    ...
    n = 9 ... n is < 10 ... assign value
    n = n + 1
    n = 10 ... n is not < 10 ... exit loop

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault when entering a for loop
    By rehpot in forum C Programming
    Replies: 6
    Last Post: 02-17-2011, 09:59 PM
  2. Replies: 9
    Last Post: 02-22-2009, 11:50 PM
  3. segmentation fault in for loop
    By Rpog in forum C Programming
    Replies: 3
    Last Post: 04-20-2004, 06:21 AM
  4. segmentation fault and memory fault
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 04-02-2002, 11:09 PM
  5. Loop until enter correct value
    By jchanwh in forum C Programming
    Replies: 2
    Last Post: 11-27-2001, 01:23 AM