>
>
>
V541. String is printed into itself. Co…


V541. String is printed into itself. Consider inspecting the expression.

The analyzer detected a potential error: a string gets printed inside itself. This may lead to unexpected results.

Look at this sample:

char s[100] = "test";
sprintf(s, "N = %d, S = %s", 123, s);

In this code, the 's' buffer is used simultaneously as a buffer for a new string and as one of the elements making up the text. The programmer intends to get this string:

N = 123, S = test

But actually this code will cause creating the following string:

N = 123, S = N = 123, S =

In other cases, such code can lead not only to the output of incorrect text, but also to the buffer overflow or a program crash. To fix the code, we should use a new buffer to save the result. This is the correct code:

char s1[100] = "test";
char s2[100];
sprintf(s2, "N = %d, S = %s", 123, s1);

This diagnostic is classified as:

You can look at examples of errors detected by the V541 diagnostic.