Skip to content

Commit c553628

Browse files
committed
Use sizeof for buffer lengths in snprintf
Rather than duplicating the constant value, use the `sizeof` operator to have the value propogate from the static buffer allocation. Any standards conforming implementation of `snprintf` will null-terminate the output unless the buffer is NULL (a zero-sized buffer is passed to the call). On Windows, where this is not the case, the function is named `_snprintf` which ensures that we do not accidentally end up with the incorrect behaviour.
1 parent e9fff22 commit c553628

File tree

3 files changed

+4
-5
lines changed

3 files changed

+4
-5
lines changed

lib/Basic/Demangle.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,13 @@ static void unreachable(const char *Message) {
3737

3838
DemanglerPrinter &DemanglerPrinter::operator<<(unsigned long long n) & {
3939
char buffer[32];
40-
snprintf(buffer, 32, "%llu", n);
40+
snprintf(buffer, sizeof(buffer), "%llu", n);
4141
Stream.append(buffer);
4242
return *this;
4343
}
4444
DemanglerPrinter &DemanglerPrinter::operator<<(long long n) & {
4545
char buffer[32];
46-
snprintf(buffer, 32, "%lld",n);
46+
snprintf(buffer, sizeof(buffer), "%lld",n);
4747
Stream.append(buffer);
4848
return *this;
4949
}

lib/Sema/PlaygroundTransform.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -889,7 +889,7 @@ class Instrumenter {
889889
std::pair<PatternBindingDecl*, VarDecl*>
890890
buildPatternAndVariable(Expr *InitExpr) {
891891
char NameBuf[11] = { 0 };
892-
snprintf(NameBuf, 11, "tmp%u", TmpNameIndex);
892+
snprintf(NameBuf, sizeof(NameBuf), "tmp%u", TmpNameIndex);
893893
TmpNameIndex++;
894894

895895
Expr *MaybeLoadInitExpr = nullptr;

stdlib/public/runtime/Reflection.mm

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -437,8 +437,7 @@ void swift_TupleMirror_subscript(String *outString,
437437

438438
// The name is the stringized element number '.0'.
439439
char buf[32];
440-
snprintf(buf, 31, ".%zd", i);
441-
buf[31] = 0;
440+
snprintf(buf, sizeof(buf), ".%zd", i);
442441
new (outString) String(buf, strlen(buf));
443442

444443
// Get a Mirror for the nth element.

0 commit comments

Comments
 (0)