From 4f77ccbda81b6721992dcc93958ef1ae9b20066f Mon Sep 17 00:00:00 2001 From: Ben Wiederhake Date: Sun, 16 Aug 2020 18:18:07 +0200 Subject: [PATCH] LibC+Userland: Prefer snprintf over sprintf I ignored the sprintf in Userland/cal.cpp because it's too much trouble. However, this only underlines the need for bounds checking. --- Libraries/LibC/netdb.cpp | 4 +++- Userland/seq.cpp | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Libraries/LibC/netdb.cpp b/Libraries/LibC/netdb.cpp index 409e068da97..ed1799205ab 100644 --- a/Libraries/LibC/netdb.cpp +++ b/Libraries/LibC/netdb.cpp @@ -100,7 +100,9 @@ hostent* gethostbyname(const char* name) { auto ipv4_address = IPv4Address::from_string(name); if (ipv4_address.has_value()) { - sprintf(__gethostbyname_name_buffer, "%s", ipv4_address.value().to_string().characters()); + auto ip4_string = ipv4_address.value().to_string(); + ASSERT(ip4_string.length() < sizeof(__gethostbyname_name_buffer)); + strncpy(__gethostbyname_name_buffer, ip4_string.characters(), ip4_string.length()); __gethostbyname_buffer.h_name = __gethostbyname_name_buffer; __gethostbyname_buffer.h_aliases = nullptr; __gethostbyname_buffer.h_addrtype = AF_INET; diff --git a/Userland/seq.cpp b/Userland/seq.cpp index 2f6d1c40dd8..b67935ab570 100644 --- a/Userland/seq.cpp +++ b/Userland/seq.cpp @@ -35,7 +35,7 @@ static double get_double(const char* name, const char* d_string, int* number_of_ char* end; double d = strtod(d_string, &end); if (d == 0 && end == d_string) { - fprintf(stderr, "%s: invalid double vallue \"%s\"\n", name, d_string); + fprintf(stderr, "%s: invalid double value \"%s\"\n", name, d_string); exit(1); } if (char* dot = strchr(d_string, '.')) @@ -95,7 +95,7 @@ int main(int argc, const char* argv[]) double d = start; for (int i = 0; i <= n; ++i) { char buf[40]; - sprintf(buf, "%f", d); // FIXME: Serenity's printf() doesn't seem to handle %f correctly: For `seq 1 0.1 2` this always prints "1.0" as `d` goes from 1.0 to 2.0. + snprintf(buf, sizeof(buf), "%f", d); if (char* dot = strchr(buf, '.')) { if (number_of_decimals == 0) *dot = '\0'; @@ -105,4 +105,6 @@ int main(int argc, const char* argv[]) printf("%s\n", buf); d += step; } + + return 0; }