1

I've been having some trouble with a program I'm making. Every time I try to compile it, I keep getting Segmentation Fault 11. I don't know why this is happening. I'm using Code Block IDE and whenever I Build and run, segmentation fault 11 continues to arise. Any ideas on how I can remedy this?

#include <stdio.h> #define NUMTEMPS 2881 int main(void){ //opening the file with temperatures FILE * ifp; ifp = fopen("temp.txt", "r"); //Declaring variables int i,j; int pct, num30 = 0, count_ac_h = 0, count_ac_t = 0, current_h = 0; int ac_on = 0, count_ac = 0; double temps[2881], pct_hr[24], diff, current_temp, previous_temp; //Checking the temperature from the .txt file and counting the occurences for (i = 0; i < 2881; ++i){ fscanf(ifp, "%lf", &temps[i]); } previous_temp = temps[0]; for (i = 0; i < 2881; ++i){ if (num30 == 120){ count_ac_t += count_ac_h; pct_hr[current_h] = (double)(count_ac_h/120); current_h++; count_ac_h = 0; num30 = 0; } current_temp = temps[i]; diff = previous_temp - current_temp; if(diff > -0.5 && diff <0.5){ if(ac_on == 1){ count_ac_h++; } } else if (diff <= -0.5){ if (ac_on == 0){ ac_on = 1; count_ac_h++; } } else if (diff >= 0.5){ if(ac_on == 1) ac_on = 0; } num30++; previous_temp = current_temp; } // Creating the bar graph based on results from above double pct_day = (double)(count_ac/NUMTEMPS); for (i = 20; i >= 0; i--){ pct = i*5; for (j = 0; j < 24; ++j){ if (pct > (pct_hr[j]*100)) printf("_"); else printf("*"); } printf("\n"); } return 0; } 
5
  • Run it under a debugger, it should tell you where (and why) it is crashing. Segmentation faults are typically due to using bad pointers. Commented Mar 19, 2014 at 19:16
  • Why #define NUMTEMPS to be 2881 and then continue to use the literal all over your code? Just use NUMTEMPS! Commented Mar 19, 2014 at 19:16
  • Which debugger would you recommend? Commented Mar 19, 2014 at 19:17
  • 1
    j is initialized at the top with i. Commented Mar 19, 2014 at 19:20
  • I would use gdb if you're on linux. If you run it there it'll tell you the exact line where you segfault. Commented Mar 19, 2014 at 21:22

2 Answers 2

3
for (i = 20; i >= 0; i--){ pct = i*5; for (i = 0; i < 24; ++i){ if (pct > (pct_hr[j]*100)) printf("_"); else printf("*"); } 

check this loop, use different loop variables for nested loops. here j is uninitialized so if it takes random large value it will result is segmentation fault.

Sign up to request clarification or add additional context in comments.

1 Comment

@user3230393 ok. dont make changes to question to reflect the suggestions from answer. it makes the answer irrelevant. so roll back your question to original state.
1

This line:

pct_hr[current_h] = (double)(count_ac_h/120); 

How can you be sure current_h is never greater than 23?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.