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.
This commit is contained in:
Marco Wang 2020-05-08 14:50:55 +08:00
parent 3ba8976592
commit 2e87f98fe4
2 changed files with 8 additions and 6 deletions

View File

@ -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<void*>(NULL));
sprintf(ptr_str, "%p", reinterpret_cast<void*>(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<void*>(NULL));
snprintf(ptr_str, str_size, "%p", reinterpret_cast<void*>(PTR_TEST_VALUE));
StringReplace(&line, "__NULLP__", null_str);
StringReplace(&line, "__PTRTEST__", ptr_str);

View File

@ -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);