On Fri, 4 Dec 1998, Doin' the Bull Dance, Feelin' the Flow... wrote:

> typedef struct word{
>     int size;
>     char *WordGuessed;
>     char *WordToGuess;
> }Word;
> 
> Word* init_word(FILE * in){
> 
>  Word * readword;
>  char word_array[BUFF_LENGTH+1], temp_array[BUFF_LENGTH+1];
>  int word_array_length, inc = 0;
>  char dashes = '_';
> 
>  fscanf(in, "%s", word_array);
> 
Not the problem, but...
This line is a potentioal problem.  If the file in contains something
longer than BUFF_LENGTH+1 bytes, your progam's behaviour will be
unpredicatble as you will read beyond the end of word_array.  This sort of
bug is the basis of many security holes, and should be avoided.
In this example, it would be safer (and probably easier) to use
   fgets(word_array, BUFF_LENGTH+1, in);

>  word_array_length = 1 + strlen(word_array);
> 
>  readword->WordToGuess = malloc(sizeof(char) * word_array_length);
>
readword is an uninitialized pointer, so this is trying to write to some
random place in memory which will cause a segmentation fault.
There are two possible solutions: 
either declare readword as being Word readword rather than Word * readword
and then use readword.WordToGuess here, or (better) allocate the memory
for readword using readword = malloc(sizeof(Word)); before this line.
 
> strcpy (readword->WordToGuess, word_array);
> 
Another potential problem.  What happens if you don't have enough memory,
and malloc returns NULL?  The program will crash out at this point because
it will try to write to memory it doesn't own.  You should always check
the return value of malloc.

>  readword->size = 1 + strlen(readword->WordToGuess);
>  printf("The word to guess is %d letters long.\n\n", readword->size - 1);
> 
> 
>  for (inc = 0; inc <= word_array_length; inc++)
>   temp_array[inc] = dashes;
> 
>  printf("%s\n\n", temp_array);
> 
>  readword->WordGuessed = malloc(sizeof(char) * word_array_length);
>  strcpy(readword->WordGuessed, temp_array);
> 
>  return readword;
> 
> }
> 

HTH

--
Mike <[EMAIL PROTECTED]>

Worth seeing?  Yes, but not worth going to see.

Reply via email to