the ayylien
the ayylien

Reputation: 13

C program crashes in a do while loop

I am trying to create a hangman game but my program keeps crashing when it gets to the for loop. I'm still reading about pointers and don't understand them completely. I know you can't modify string literals so I tried making modifiable arrays, but I'm pretty sure the crashing is related to this. Could anyone point out a specific cause to the crash?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(int argc, char **argv)
{
  char word[15];
  char *wordState = malloc(15);
  char *guess[1];
  int guesses = 6;
  int i;
  printf("Enter word.\0");
  scanf("%s",word);
  strcpy(wordState, "---------------");
  do{
    printf("Please guess a letter.\0");
    printf("You have %d\n guesses.\0", guesses);
    scanf("%s\n",guess);
    printf("%s\n", wordState);
    for(i=0; word[i] != '\0'; i++)
      {
       if(*guess[1]==word[i])
         {
           strcpy(*wordState[i],*guess[1]);
         }
       else
         {
           guesses--;
         }
      }
    }while(guesses != 0);

  free(wordState);

Upvotes: 1

Views: 334

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134376

Mostly, your problem is because,

strcpy(wordState, "---------------");

as you don't have enough space to copy the \0 and essentially creating memory overrun.

Again, with a definition like char *guess[1];, using

if(*guess[1]==word[i])

is undefined behaviour, because

  1. C arrays are 0 based. [Think: why do you want 1-element array, anyway?]
  2. You're using uninitialized memory.

There are some other issues I can notice, like

  1. void main(int argc, char **argv) should be int main(int argc, char **argv)
  2. You did not check for the success of malloc()
  3. scanf("%s",word); should be scanf("%14s",word); to avoid possible buffer overrun by longer input.

Upvotes: 4

&#212;rel
&#212;rel

Reputation: 7642

Simplify guess, deal with letter seen more than one time

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdbool.h> 

void main(int argc, char **argv) 
{ 
    char word[16]; 
    char *wordState = malloc(16 * sizeof(char)); 
    char guess; 
    int guesses = 6; 
    printf("Enter word.\n"); 
    scanf("%s",word); 
    strcpy(wordState, "---------------"); 
    do{ 
        bool found = false; 
        printf("Please guess a letter.\n"); 
        printf("You have %d guesses.\n", guesses); 
        scanf(" %c", &guess); 
        for(int i=0; word[i] != '\0'; i++) 
        { 
            if(word[i] == guess) 
            { 
                wordState[i] = guess; 
                found = true; 
            } 
        } 
        if (!found) 
        { 
            guesses--; 
        } 
        printf("%s\n", wordState); 
    } while(guesses != 0); 

    free(wordState); 
}   

Upvotes: 0

Related Questions