[sprintf] Wrong handling of "+" flag for unsigned specifiers

Open Beginner friendly
#17 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
Under an hour
Newbie friendliness
68/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
c
Domain
tooling

Research direction

The flag handling lives in stb_sprintf.h, around lines 1056-1057, where the STBSP__LEADINGPLUS flag is set for conversions. Read that section, then compile a small program with the three printf calls from the issue and compare the output with a standard-conforming libc. Done means %+u, %+-10u and %+010u match the standard's behaviour that the issue describes. The issue notes that the standard may leave this as undefined behaviour, so check that question before changing anything.

Written by the indexing model from the issue text.

Description

The standard says:

+ The result of a signed conversion always begins with a plus or minus sign. (It begins with a sign only when a value with a negative sign is converted if this flag is not specified.)

This seems to mean that unsigned conversions should ignore the '+' flag, though it could also be UB (this whole section of the standard is very lousy regarding more-or-less corner cases).
Other implementations seem to agree on ignoring '+'.

Also, the '+' and '-' flags do orthogonal things. The standard doesn't explicitly describe their coexistence, but it seems quite clear that they should both be respected.

STB vs standard-conforming:

printf("%+-10u", 1);  // "+1        " vs "1         "
printf("%+10u", 1);   // "        +1" vs "         1"
printf("%+010u", 1);  // "+000000001" vs "0000000001"

Fix for both issues: in between lines 1056-1057:
https://github.com/nothings/stb/blob/f0569113c93ad095470c54bf34a17b36646bbbb5/stb_sprintf.h#L1056-L1057
clear the STBSP__LEADINGPLUS flag:

fl &= ~STBSP__LEADINGPLUS;
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.