[sprintf] Wrong handling of non-default-size %n

Open
#31 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
Half a day
Newbie friendliness
42/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
c
Domain
backend

Research direction

The bug is in the %n branch of stb_sprintf.h, around line 615, which always writes through an int* regardless of the hh, h, l or ll length modifiers. Read how the length modifiers are parsed and where the n conversion consumes its va_arg, then make each modifier store through the matching pointer type (signed char, short, long, long long). Done when a small test program that passes %hhn, %hn, %ln and %lln writes the correct width and the file still builds as a single header.

Written by the indexing model from the issue text.

Description

The standard states that 'hh' 'h' 'l' 'll' also apply to %n, in which case the argument must be treated as (signed char*), (short*), (long*), (long long*), respectively.
See line 615 of stb_sprintf.h, where 'n' is always treated as (int*):
https://github.com/nothings/stb/blob/f0569113c93ad095470c54bf34a17b36646bbbb5/stb_sprintf.h#L615-L619

Also note that (signed char*) is different from plain (char*), and that the standard mandates (signed char*).

Finally, note that accessing a variadic argument with va_arg is undefined behavior for any type that is small --ie that a call with variadic arguments automatically promotes to a larger type (as char->int, short->int, float->double, etc.). So, the fetching of an 'hhi' argument, needed to fix the current issue, will have to be done as:

signed char v = (signed char)va_arg(va, int);

and not as

signed char v = (signed char)va_arg(va, signed char);
Dominant language
C
Stars
18
Forks
5
Avg merge
1m
Merged PRs (30d)
3

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from nothings/stb_sprintf

All issues in nothings/stb_sprintf

Similar issues

More C issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.