eklmp
eklmp

Reputation: 201

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.

Upvotes: 0

Views: 100

Answers (2)

Ant
Ant

Reputation: 4928

You are writing into char array xx as well as using it as the source for the copy. This behaviour is undefined. Here's an existing question about the situation:

Is sprintf(buffer, "%s […]", buffer, […]) safe?

Upvotes: 1

Simon Richter
Simon Richter

Reputation: 29598

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.

Upvotes: 1

Related Questions