Have a look at this code:
char *c = "%c %s %c";
char *r = malloc(100 * sizeof(char));
printf(c, 65, c, 66);
It works as I expect and prints A %c %s %c B. But when I try to use sprintf:
char *c = "%c %s %c";
char *r = malloc(100 * sizeof(char));
sprintf(r, c, 65, c, 66);
printf(r);
It outputs A B.
I know that if copying takes place between objects that overlap the results are undefined. I don't know if this applies to my case, since the source and destination don't overlap, only the format string and one of the arguments. My main question is how can I have the printf behavior without printing, but storing the result to memory. Btw I also tried with sprintf and it works unexpected as well.
With
sprintf(r, c, 65, c, 66);
you indeed make r contain the string you expect. But then you do
printf(r);
which will interpret the % sequences in the string r and attempt to find matching arguments for it. Since there are no arguments passed you will have undefined behavior.
If you want to just print the string in r as it is, use e.g. puts instead:
puts(r);
This is the reason you should never pass a string input by a user as the format string to a printf family function. It's an incredibly bad security hole.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With