C question: why is my 20 length string limits itself with 6 chars?

Viewed 65

I am trying to make my own str_to_upper function but when i write something longer than 5 characters it only returns the first 5 chars and a '\0' char. I guess word[5] should be '\0' and that means my code returns a 6 char length string but i don't understand where that '\0' comes from.

my code:

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

char *str_to_upper(char *);

int main()
{
    char word[20];

    puts("Please enter a word: ");
    fgets(word, strlen(word), stdin);

    puts(str_to_upper(word));

    return 0;
}

char *str_to_upper(char *sentence)
{
    int length=strlen(sentence);

    for(int i=0; i<length; i++)
    {
        sentence[i]=toupper(sentence[i]);
    }

    return sentence;
}

output:

Please enter a word: 
aaaaaaaaaaa  
AAAAA

when i put a for loop to write inside my array i get:

Please enter a word:
aaaaaaaaaaa
AAAAA
AAAAA0��}y
1 Answers

Just substitute your

fgets(word, strlen(word), stdin);

with

fgets(word, sizeof(word), stdin);

In fact, strlen returns the length of a string (word) not initialized. So, current limit of fgets is a consequence of what you have in your stack.

Related