[sprintf] Wrong handling of multiple flags including '0'

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

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
72/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
c
Domain
tooling

Research direction

The bug is in flag parsing in stb_sprintf.h, around lines 490-494, where the '0' flag is handled. Read that block, then compile a small C program that calls the library's sprintf with the four cases in the issue ("%0-10x", "%0+10x", "%0 10x", "%0#10x") and compare against the C standard library output. Done when all four match the standard, with '0' treated as a flag in any position.

Written by the indexing model from the issue text.

Description

The standard says:

After the %, the following appear in sequence:
— Zero or more flags (in any order) that modify the meaning of the conversion specification.
— An optional minimum field width. […]

And:

Note that 0 is taken as a flag, not as the beginning of a field width.

So, the '0' can be in any order relative to the other flags, and it does not mark the end of the flags.

STB vs standard-conforming:

printf("%0-10x", 1); // "-10x" vs "1         "
printf("%0+10x", 1); // "+10x" vs "0000000001"
printf("%0 10x", 1); // " 10x" vs "0000000001"
printf("%0#10x", 1); // "#10x" vs "0x00000001"

Fix: change line 493:
https://github.com/nothings/stb/blob/f0569113c93ad095470c54bf34a17b36646bbbb5/stb_sprintf.h#L490-L494
to:

continue;
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.