Wireshark-dev: Re: [Wireshark-dev] Sprintf weirdness

From: Guy Harris <guy@xxxxxxxxxxxx>
Date: Tue, 1 Jun 2010 21:57:09 -0700
On Jun 1, 2010, at 9:01 PM, Ian Schorr wrote:

> For example, I have 4 variables:
> - string mystring, with value "LOCK"
> - guint32 last_fh_hash, with value "2056735708"
> - guint64 file_offset, with value 0
> - guint64 lock_length, with value 10
> 
> The weird thing is that when I do this:
> 
> sprintf (mystring, "%s FH: 0x%08x Offset: %lu Length: %lu",
> mystring,last_fh_hash,file_offset,lock_length);

You're assuming here that a guint64 is of type "long".  It's only of type "long" on 64-bit UN*X systems; it's "long long" on 32-bit UN*X systems, and some other 64-bit type on 32-bit *AND* 64-bit Windows ("long" is 32 bits on Windows, even 64-bit Windows).

If you want the code to be portable, you'd have to hope that Microsoft provides the C99 PRI[doux]64 macros, even though Visual Studio doesn't claim to support C99, and use them, as per Eloy Paris' suggestion, or you'd have to define them yourself and use #ifdefs to select different definitions for different platforms (if you care about, for example, fairly old versions of *BSD, it might be complicated, but I think on any reasonably modern UN*X %ll[doux] would work; on Windows, it won't work - it's something like %I64[doux]).

This means that anything could happen.

(Oh, and one more thing: unless you absolutely positively certainly know that the string in question can never never never never ever go past the end of "mystring", use snprintf.)