Search code examples
cc

why does the following program give error when it is checked with cppcheck analyzer


#include "stdio.h"

int main (void) {
    char xx[1000] = "hello";
    sprintf (xx, "xyzzy plugh %s", xx);
    printf ("%s\n", xx);
    return 0;
}

::::(error) Undefined behaviour: xx is used wrong in call to sprintf or snprintf. Quote: If copying takes place between objects that overlap as a result of a call to sprintf() or snprintf(), the results are undefined.


Solution

  • Precisely what it says. You are passing the same array both as input and output to sprintf(), which is not a supported usage as there is no guarantee that sprintf will write the output string in ascending order.