argamanza
argamanza

Reputation: 1142

Function that needs to putt limited length strings doesn't work well

I've got this function i created:

void getWords(int words){
    int remaining, error=0;
    char word[WORD_MAX+1], def[DEF_MAX+1];

    for(remaining = words;remaining > 0;remaining--){
        do{
            printf("Enter definition #%d out of %d:\n",((words+1) - remaining),words);
            gets(word);
            if(strlen(word) > WORD_MAX){
                error = 1;
                printf("\nError! '%s' contains %d characters | Maximum allowed: %d | Please try again...\n\n",word,strlen(word),WORD_MAX);
            }
        }while(error);
    }
}

It does what it should do basically, checks if the string length is at most 'WORD_MAX' characters long and if not asks the user to do it again, My problem is this:

when i tested it with WORD_MAX of 3 and tried to write a 6 characters long string it works perfectly, but when i tried to write a really long string, for example 20 chars long, it wrote only some of the word, with some weird ascii smiley on the end, and the 'remaining' variable which contains the number of words i ask the function to input get some garbage value and it ruins the whole program, why does it do that?

Thank you!

Upvotes: 0

Views: 45

Answers (1)

simonc
simonc

Reputation: 42185

As you've noticed, there is no way to avoid buffer overflow with gets. As an alternative, you could use fgets

fgets(word, WORD_MAX+1, stdin);

From its man page

char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.

Upvotes: 3

Related Questions