Seg Faulting C. Where?
Some where in my code i am causing a memory violation and my program crashes. The word which is in the text file is test.
Can anyone help? //This is going to be hangman #include <stdio.h> main() { char answer[1000]; char guess; int bool; int i; FILE *file; file = fopen("answer", "r"); if (file == NULL) { printf("No File To Be Processed \n"); } else { printf ("File Found \n"); while(fgets(answer,1000,file)!=NULL) { printf("%s",answer); } } printf ("Welcome To Hangman \n"); printf ("Please Pick A Letter \n"); guess = getchar(); do { i=i+1; if(guess == answer[i]) { printf("Correct Guess"); bool = 0; } else { printf("%c", answer[i]); } } while(bool=1 || i < 3); } |
You are going overbounds on your answer[] array.
|
what you mean its allocated to 1000 characters and i am only using 4 (test), what should i do if you are right?
|
Hint: Your loop logic is incorrect.
|
Thanx for the hint, but as i am so new to C, i wouldn't know where or what i am looking for. Can you shed some more light on it, Thankyou.
|
Re: Seg Faulting C. Where?
Quote:
but I think it should read > while(bool==1 || i < 3); < |
Code:
#include <stdio.h> |
THANKYOU: I've done everthing you said and it still segfaults any ideas? :THANKYOU
//This is going to be hangman
#include <stdio.h> int main() { char answer[1000]; char guess; int bool; int count; //this is where i load all my variables to make my do loop work bool = 1; //reads in "test" from text file FILE *file; file = fopen("answer", "r"); if (file == NULL) { printf("No File To Be Processed \n"); } else { printf ("File Found \n"); while(fgets(answer,1000,file)!=NULL) { printf("%s",answer); } } //starts hangman printf ("Welcome To Hangman \n"); printf ("Please Pick A Letter \n"); guess = getchar(); //validation to make sure the answer is correct to the inputted answer do { count++; if(guess == answer[count]) { printf("Correct Guess"); bool = 0; } else { printf("%c", answer[count]); } } while((bool == 1) || (count < 3)); return 0; } |
Quote:
Please use code tags when posting code. Also, you don't initialize count. Automatic variables start with a garbage value so they must be initialized before you use them. |
I just took a quick glance through your new code and you're still NOT giving all your variables a starting value. count is not being set to 0 before the increment operator (++) is being used. Hence, count could be any value and hence could very well be bigger than 1000 and hence crashing your program with a seg fault error.
Like what itsme86 is saying, good programming practise is to do all declaration of variables at the start quickly followed by their initialization to a starting value. |
All times are GMT -5. The time now is 10:15 AM. |