From 2e87f98fe49cfd25ebb045c3eebd4bf2a5956ac4 Mon Sep 17 00:00:00 2001 From: Marco Wang Date: Fri, 8 May 2020 14:50:55 +0800 Subject: [PATCH] Replace sprintf() with snprintf() (#536) sprintf poses two security risks: (1) write to memory where it shouldn't (2) read from memory where it shouldn't This commit replaces the use of sprintf() with snprintf() which has a size parameter to ensure the problems mentioned above won't take place. --- src/googletest.h | 9 +++++---- src/stl_logging_unittest.cc | 5 +++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/googletest.h b/src/googletest.h index a9e7795dc..72306063c 100644 --- a/src/googletest.h +++ b/src/googletest.h @@ -448,10 +448,11 @@ static inline string Munge(const string& filename) { string result; while (fgets(buf, 4095, fp)) { string line = MungeLine(buf); - char null_str[256]; - char ptr_str[256]; - sprintf(null_str, "%p", static_cast(NULL)); - sprintf(ptr_str, "%p", reinterpret_cast(PTR_TEST_VALUE)); + const size_t str_size = 256; + char null_str[str_size]; + char ptr_str[str_size]; + snprintf(null_str, str_size, "%p", static_cast(NULL)); + snprintf(ptr_str, str_size, "%p", reinterpret_cast(PTR_TEST_VALUE)); StringReplace(&line, "__NULLP__", null_str); StringReplace(&line, "__PTRTEST__", ptr_str); diff --git a/src/stl_logging_unittest.cc b/src/stl_logging_unittest.cc index 269094c07..05acc134e 100644 --- a/src/stl_logging_unittest.cc +++ b/src/stl_logging_unittest.cc @@ -135,8 +135,9 @@ static void TestSTLLogging() { for (int i = 0; i < 100; i++) { v.push_back(i); if (i > 0) expected += ' '; - char buf[256]; - sprintf(buf, "%d", i); + const size_t buf_size = 256; + char buf[buf_size]; + snprintf(buf, buf_size, "%d", i); expected += buf; } v.push_back(100);