Olaf wrote:
...
does exist a safe version/way of sprintf to prevent a buffer overflow by
using in this manner?
char* format = "0x%0.4X\n";
char buf[4];
sprintf(buf, format, number);
where the format can change at runtime? The buf size is fixed at compile
time.
...
There are always at least two ways "to prevent a buffer overflow". One is the
make sure that your buffer is always big enough for the data you are trying to
write into it. Another is to truncate the data when it hits the limit of the
buffer. The first question you should be asking yourself is which one you really
need.
The latter prevention strategy is of very limited use since, even tough it does
prevent the overflow, it usually provides no useful result and no meaningful
continuation strategy. It is mostly useful in situations when you want to abort
your program anyway, but you'd prefer to exit more-or-less gracefully with your
own diagnostic message instead of the inelegant "segmentation fault, core dumped".
If that's not what you want to do (is it?), then you'd better off sticking with
the former strategy. Which brings the question of where is the requirement of
the buffer size being fixed at compile time comes from?
--
Bes? regards,
Andrey Tarasevich