Home > Software design >  Why edited string added after another string
Why edited string added after another string

Time:05-02

I was trying to get input from user but when i set a variable for it it also adds it self to another variable

Code

#include <stdio.h>

int main()
{

    printf("Enter String: ");
    char a[10];
    scanf("%s", a);

    char t[8] = "00:00:00";
    printf("%s\n", t);

}

Terminal

enter string: asd
00:00:00asd

CodePudding user response:

Because "00:00:00" needs 9 space (including the terminating '\0' ) and you only give it 8.

CodePudding user response:

Your computer stores the variables on the stack. All variables are added to stack but the stack grows to the lowest addresses.

Until the scanf, the stack lookes like:

Variable a:

Address Offset Value
00 ??
-6 0
-7 'd'
-8 's'
-9 'a'

The scanf function reads in a line and terminates it with a '0' character which equals 0. That's why we have a 0 in cell -6 The upper addresses are not used because your input line has only three characters and the terminating 0.

Now comes the variable t:

Address Offset Value
-10 '0'
-11 '0'
-12 ':'
-13 '0'
-14 '0'
...

As you can see, we get a contigous block of memory starting from -17 to -6 with the the string "00:00:00asd" and a terminating 0.

This block is being printed 00:00:00asd. This issue is called buffer overflow or especially string overflow.

You can fix it with this modified code but you will have similiar issues if you enter a line during during scanf that is longer than 9 characters.

#include <stdio.h>

int main()
{

    printf("Enter String: ");
    char a[10];
    scanf("%s", a);

    char t[9] = "00:00:00";
    printf("%s\n", t);

}
florian@florian-desktop:~$ ./a.out 
Enter String: asdfasdfasd
00:00:00
*** stack smashing detected ***: terminated

Instead you could use fgets: How to read from stdin with fgets()? (Steve Emmersons answer)

  • Related