Search code examples
ccollisionstdio

Is it safe to use format parameter as additional argument in sscanf?


Is the following code safe to use? I mean if the pattern might be scanned and overwriten in one loop, or if such collision never occurs, or if it is implementation dependent.

char pattern[32] = "%31s";
sscanf("hello",pattern,pattern);

I didn't find any note about that here nor here.

(Use case: sometimes I use pattern as temporary buffer.)


Solution

  • The C11 standard (ISO/IEC 9899:2011) covers this. It says:

    7.21.6.7 The sscanf function

    int sscanf(const char * restrict s, const char * restrict format, ...);
    

    The restrict means that the format can't be the same as any of the arguments.

    The description says:

    If copying takes place between objects that overlap, the behavior is undefined.

    What you're trying to do is 'undefined behaviour'. Don't do that.