0
#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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It also makes very little sense to do this in this way. Normally you have a char array to receive the formatted strings and the parameters to your format string as parameters coming from something. Perhaps update your function to take console args and put those in to do the string formatting and use snprintf to make it safe for overflow situations.
1

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.