replace `sprintf` with `snprintf`
Nobody has claimed this yet.
- Dominant language
- C
- Stars
- 6.5k
- Forks
- 627
- Avg merge
- 3d 21h
- Merged PRs (30d)
- 6
Description
Question
The h3ToString function uses sprintf(). Is it possible / worth replacing with snprintf() ?
H3Error H3_EXPORT(h3ToString)(H3Index h, char *str, size_t sz) {
// An unsigned 64 bit integer will be expressed in at most
// 16 digits plus 1 for the null terminator.
if (sz < 17) {
// Buffer is potentially not large enough.
return E_MEMORY_BOUNDS;
}
sprintf(str, "%" PRIx64, h); // <-- replace with `snprintf(str, sizeof(str), "%" PRIx64, h);` ?
return E_SUCCESS;
}
For example, as noted in https://rules.sonarsource.com/c/RSPEC-6069/,
When using sprintf , it’s up to the developer to make sure the size of the buffer to be written to is large enough to avoid buffer overflows. Buffer overflows can cause the program to crash at a minimum. At worst, a carefully crafted overflow can cause malicious code to be executed.
(I'm not a full-on C-programmer, so it may be the case that the sz < 17, and the H3Index h (uint64_t) themselves guarantee this overflow won't occur?)
Usecase / Background
I'm building an R library using h3, but upcoming versions of R* won't accept sprintf in compiled code due to the security risk.
* Not strictly R itself, but rather the official repositry of R packagse, CRAN
Use of sprintf and vsprintf is regarded as a potential security risk and warned about on some platforms.82 (including macOS as from version 13).
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with h3ToString in src/h3lib/lib/h3Index.c, especially the existing sz < 17 check and sprintf call. Verify that the string output remains correct and that the change removes the sprintf use without altering the function's return behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c
- Domain
- api
- Issue type
- Refactor
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100