ANNOUNCEMENT: Live Wireshark University & Allegro Packets online APAC Wireshark Training Session
April 17th, 2024 | 14:30-16:00 SGT (UTC+8) | Online

Wireshark-dev: Re: [Wireshark-dev] g_snprintf() and sizeof

From: Guy Harris <guy@xxxxxxxxxxxx>
Date: Fri, 20 Mar 2009 11:13:09 -0700

On Mar 19, 2009, at 5:27 PM, Guy Harris wrote:


On Mar 19, 2009, at 1:54 PM, Stephen Fisher wrote:

Stop using fixed length strings so much? :-)

Even if we cast them now, I can see people adding sizeof in the future
and forgetting to cast it.  GLib doesn't appear to have any other
solution.

I suspect a lot of the g_snprintf() is to generate formatted strings
and put them into places such as the Info column and the display form
of protocol tree items, and I suspect a lot of those calls generate
strings by producing an initial string and appending to them.  The
idiom used for the latter is really ugly.

GLib has the GString type, which, other than doing g_mallocs which
could leak if the dissector throws an exception, are probably the
right type for this.  Perhaps we should create an ep_string type or
something such as that, which is a string similar to a GString to
which you can append stuff, with the string expanding as necessary,
and use that to replace those g_snprintf()s?

...although, in some of those cases, you might *want* fixed-length strings. If what's being generated is a string that would appear in the Info column or in a protocol tree item with a bunch of subitems, and it has a list of subitems followed by other information, you might not want it to include all the subitems if there are so many that this would push the information following the subitems too far to the right (or past the maximum length of the column or protocol tree item's display field).

For those, you might want another type, with a similar "append to this" API, but with a maximum length, with the "append to this" API just adding a "..." and returning an error if the maximum length would be exceeded (or if it wouldn't even leave enough room for a "..."), so that the loop adding items could terminate (or, if parsing the items is useful for other purposes, at least stop trying to append).