[ACCEPTED]-Is sprintf(buffer, "%s […]", buffer, […]) safe?-c-strings

Accepted answer
Score: 24

From the glibc sprintf() documentation:

The behavior of this function 18 is undefined if copying takes place between 17 objects that overlap—for example, if s 16 is also given as an argument to be printed 15 under control of the ‘%s’ conversion.

It 14 may be safe in a particular implementation; but 13 you could not count on it being portable.

I'm 12 not sure that your proposal would be safe 11 in all cases either. You could still be 10 overlapping buffers. It's late and my wife 9 is buggin me but I think that you could 8 still have the case where you want to use 7 the original string again in the concatenated 6 string and are overwriting the null character 5 and so the sprintf implementation might 4 not know where the re-used string ends.

You 3 might just want to stick with a snprint() to 2 a temp buffer, then strncat() it onto the 1 original buffer.

Score: 5

In this specific case, it is going to work 6 because the string in buffer will be the first 5 thing that is going to enter in buffer (again, useless), so 4 you should use strcat() instead to get the [almost] same 3 effect.

But, if you are trying to combine 2 strcat() with the formating possibilities of sprintf(), you 1 may try this:

sprintf(&buffer[strlen(buffer)], " <input type='file' name='%s' />\r\n", id);
Score: 3

If you want to concatenate formatted text 7 to the end of a buffer using printf(), I'd 6 recommend you use an integer to keep track 5 of the end position.

int i = strlen(buffer);
i += sprintf(&buffer[i], " <input type='file' name='%s' />\r\n", id);
i += sprintf(&buffer[i], "</td>");


int i = strlen(buffer);
i += sprintf(&buffer[i], " <input type='file' name='%s' />\r\n", id);
strcat(&buffer[i], "</td>");

And before people 4 go berserk downvoting this ("This isn't 3 safe! You can overrun the buffer!"), I'm 2 just addressing a reasonable way to build 1 a formatted string in C/C++.

More Related questions