Search code examples
cstrcpy

How can a string appear longer than its declared length?


I have declared the same size of two char strings (str1 and str2). After that, I read a string through gets() function and store it on str1 then copy str1 to str2. when they are displayed, I realized str2 can store more characters than its size?

This is my code:

#include<stdio.h>
#include<string.h>
void main()
{
    char str1[20], str2[20];
    printf("Enter the first string:");
    gets(str1);
    strcpy(str2,str1);
    printf("First string is:%s\tSecond string is:%s\n",str1,str2);
}

The output here:

Enter the first string: Why can str2 store more characters than str1?
First string is:ore characters than str1?       Second string is:Why can str2 store more characters than str1?

thank everyone in advance


Solution

  • First of all, as already pointed out in the comments section, you should never use gets in modern C code. That function is so dangerous that it has been removed from the ISO C standard. A safer alternative is fgets.

    When you print str2 using the %s format specifier, printf will not just print the contents of the str2 array. It will print everything it finds in memory, until it finds a null terminating character.

    Since the array str2 does not contain such a null character, it will continue printing everything it finds in memory, past the boundary of str2, until it finds a null character (unless it crashes beforehand). Since you seem to have previously written the string past the boundary of str2 (which is a buffer overflow), it will print that string, unless the memory was meanwhile overwritten by something else.