Search code examples
cscanfc-strings

Why does sscanf changing the value of original char array?


I'm not understand how sscanf works.

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

int main(void)
{

    char s[100] = "testtes te asdf newlinetest";

    char parm1[10];
    char parm2[4];
    char parm3[256];
    char parm4[10];

    printf("BEFORE: %s\n", s);
    sscanf(s, "%s %s %s %s", parm1, parm2, parm3, parm4);
    printf("AFTER: %s\n", s);

    return (0);
}

Output :

BEFORE: testtes te asdf newlinetest
AFTER: t

It seems like it is printing the last character, however when the size of parm1 to 90, it prints the correct output.

Output:

BEFORE: testtes te asdf newlinetest
AFTER: testtes te asdf newlinetest

Solution

  • param4 is not large enough to hold the string "newlinetest". As a result, when sscanf writes to it it writes past the end of the array. This triggers undefined behavior.

    In this particular case, it just so happened that s appeared immediately after param4 in memory so the first few bytes of s were overwritten. However, this is only one way the program could have behaved. It could have appeared to work properly.

    By making param4 larger, you prevent writing past the end of the array.