I have a super-simple class representing a decimal # with fixed precision, and when I want to format it I do something like this:
assert(d.DENOMINATOR == 1000000);
char buf[100];
sprintf(buf, "%d.%06d", d._value / d.DENOMINATOR, d._value % d.DENOMINATOR);
Astonishingly (to me at least) this does not work. The %06d term comes out all 0s even when d.DENOMINATOR does not evenly divide d._value. And if I throw an extra %d in the format string, I see the right value show up in the third spot — so it’s like something is secretly creating an extra argument between my two.
If I compute the two terms outside of the call to sprintf, everything behaves how I expect. I thought to reproduce this with a more simple test case:
char testa[200];
char testb[200];
int x = 12345, y = 1000;
sprintf(testa, "%d.%03d", x/y, x%y);
int term1 = x/y, term2 = x%y;
sprintf(testb, "%d.%03d", term1, term2);
…but this works properly. So I’m completely baffled as to exactly what’s going on, how to avoid it in the future, etc. Can anyone shed light on this for me?
(EDIT: Problem ended up being that d._value and d.DENOMINATOR are both long longs so %d doesn’t suffice. Thanks very much to Serge’s comment below which pointed to the problem, and Mark’s answer submitted shortly thereafter.)
Almost certainly your term components are a 64-bit type (perhaps
longon a 64-bit system) which is getting passed into the non-type-safesprintf. Thus when you create an intermediate int the size is right and it works fine.g++ will warn about this and many other useful things with
-Wall. The preferred solution is of course to use C++ iostreams for your formatting as they’re totally type safe.The alternate solution is to cast the result of your expression to the type that you told
sprintfto expect so it pulls the proper number of bytes out of memory.Finally, never use
sprintfwhen almost every compiler supportssnprintfwhich prevents all sorts of silly mistakes. Your code is fine now but when someone modifies it later and it runs off the end of the buffer you may spend days tracking down the corruption.