Quellcode durchsuchen

Merge topic 'purge-sprintf'

b7e9cd05cd Replace the only non-standard _snprintf with snprintf
5ba6e8ac59 Source: Replace most calls to sprintf with snprintf

Acked-by: Kitware Robot <[email protected]>
Merge-request: !6649
Brad King vor 4 Jahren
Ursprung
Commit
9bb7982a15

+ 1 - 1
Source/CPack/cmCPackSTGZGenerator.cxx

@@ -107,7 +107,7 @@ int cmCPackSTGZGenerator::GenerateHeader(std::ostream* os)
   cmCPackLogger(cmCPackLog::LOG_DEBUG,
                 "Number of lines: " << counter << std::endl);
   char buffer[1024];
-  sprintf(buffer, "%d", counter);
+  snprintf(buffer, sizeof(buffer), "%d", counter);
   cmSystemTools::ReplaceString(res, headerLengthTag, buffer);
 
   // Write in file

+ 4 - 2
Source/CTest/cmCTestCoverageHandler.cxx

@@ -147,7 +147,8 @@ bool cmCTestCoverageHandler::StartCoverageLogFile(
   cmGeneratedFileStream& covLogFile, int logFileCount)
 {
   char covLogFilename[1024];
-  sprintf(covLogFilename, "CoverageLog-%d", logFileCount);
+  snprintf(covLogFilename, sizeof(covLogFilename), "CoverageLog-%d",
+           logFileCount);
   cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                      "Open file: " << covLogFilename << std::endl,
                      this->Quiet);
@@ -164,7 +165,8 @@ void cmCTestCoverageHandler::EndCoverageLogFile(cmGeneratedFileStream& ostr,
                                                 int logFileCount)
 {
   char covLogFilename[1024];
-  sprintf(covLogFilename, "CoverageLog-%d.xml", logFileCount);
+  snprintf(covLogFilename, sizeof(covLogFilename), "CoverageLog-%d.xml",
+           logFileCount);
   cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
                      "Close file: " << covLogFilename << std::endl,
                      this->Quiet);

+ 5 - 4
Source/CTest/cmCTestGIT.cxx

@@ -582,16 +582,17 @@ private:
     time_t seconds = static_cast<time_t>(person.Time);
     struct tm* t = gmtime(&seconds);
     char dt[1024];
-    sprintf(dt, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year + 1900,
-            t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
+    snprintf(dt, sizeof(dt), "%04d-%02d-%02d %02d:%02d:%02d",
+             t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour,
+             t->tm_min, t->tm_sec);
     std::string out = dt;
 
     // Add the time-zone field "+zone" or "-zone".
     char tz[32];
     if (person.TimeZone >= 0) {
-      sprintf(tz, " +%04ld", person.TimeZone);
+      snprintf(tz, sizeof(tz), " +%04ld", person.TimeZone);
     } else {
-      sprintf(tz, " -%04ld", -person.TimeZone);
+      snprintf(tz, sizeof(tz), " -%04ld", -person.TimeZone);
     }
     out += tz;
     return out;

+ 6 - 4
Source/CTest/cmCTestRunTest.cxx

@@ -229,7 +229,8 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
 
   passed = this->TestResult.Status == cmCTestTestHandler::COMPLETED;
   char buf[1024];
-  sprintf(buf, "%6.2f sec", this->TestProcess->GetTotalTime().count());
+  snprintf(buf, sizeof(buf), "%6.2f sec",
+           this->TestProcess->GetTotalTime().count());
   outputStream << buf << "\n";
 
   bool passedOrSkipped = passed || skipped;
@@ -294,9 +295,10 @@ bool cmCTestRunTest::EndTest(size_t completed, size_t total, bool started)
     ttime -= minutes;
     auto seconds = std::chrono::duration_cast<std::chrono::seconds>(ttime);
     char buffer[100];
-    sprintf(buffer, "%02d:%02d:%02d", static_cast<unsigned>(hours.count()),
-            static_cast<unsigned>(minutes.count()),
-            static_cast<unsigned>(seconds.count()));
+    snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d",
+             static_cast<unsigned>(hours.count()),
+             static_cast<unsigned>(minutes.count()),
+             static_cast<unsigned>(seconds.count()));
     *this->TestHandler->LogFile
       << "----------------------------------------------------------"
       << std::endl;

+ 1 - 1
Source/CTest/cmCTestScriptHandler.cxx

@@ -411,7 +411,7 @@ int cmCTestScriptHandler::ExtractVariables()
   char updateVar[40];
   int i;
   for (i = 1; i < 10; ++i) {
-    sprintf(updateVar, "CTEST_EXTRA_UPDATES_%i", i);
+    snprintf(updateVar, sizeof(updateVar), "CTEST_EXTRA_UPDATES_%i", i);
     cmValue updateVal = this->Makefile->GetDefinition(updateVar);
     if (updateVal) {
       if (this->UpdateCmd.empty()) {

+ 2 - 2
Source/CTest/cmCTestTestHandler.cxx

@@ -623,7 +623,7 @@ void cmCTestTestHandler::LogTestSummary(const std::vector<std::string>& passed,
     this->PrintLabelOrSubprojectSummary(false);
   }
   char realBuf[1024];
-  sprintf(realBuf, "%6.2f sec", durationInSecs.count());
+  snprintf(realBuf, sizeof(realBuf), "%6.2f sec", durationInSecs.count());
   cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
                      "\nTotal Test time (real) = " << realBuf << "\n",
                      this->Quiet);
@@ -784,7 +784,7 @@ void cmCTestTestHandler::PrintLabelOrSubprojectSummary(bool doSubProject)
     label.resize(maxlen + 3, ' ');
 
     char buf[1024];
-    sprintf(buf, "%6.2f sec*proc", labelTimes[i]);
+    snprintf(buf, sizeof(buf), "%6.2f sec*proc", labelTimes[i]);
 
     std::ostringstream labelCountStr;
     labelCountStr << "(" << labelCounts[i] << " test";

+ 3 - 2
Source/CTest/cmCTestVC.cxx

@@ -123,8 +123,9 @@ std::string cmCTestVC::GetNightlyTime()
     this->CTest->GetCTestConfiguration("NightlyStartTime"),
     this->CTest->GetTomorrowTag());
   char current_time[1024];
-  sprintf(current_time, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year + 1900,
-          t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
+  snprintf(current_time, sizeof(current_time), "%04d-%02d-%02d %02d:%02d:%02d",
+           t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min,
+           t->tm_sec);
   return std::string(current_time);
 }
 

+ 1 - 1
Source/CTest/cmProcess.cxx

@@ -511,7 +511,7 @@ std::string cmProcess::GetExitExceptionString() const
     default:
       char buf[1024];
       const char* fmt = "Exit code 0x%" KWIML_INT_PRIx64 "\n";
-      _snprintf(buf, 1024, fmt, this->ExitValue);
+      snprintf(buf, sizeof(buf), fmt, this->ExitValue);
       exception_str.assign(buf);
   }
 #else

+ 5 - 3
Source/CursesDialog/cmCursesLongMessageForm.cxx

@@ -78,7 +78,8 @@ void cmCursesLongMessageForm::UpdateStatusBar()
 
   char version[cmCursesMainForm::MAX_WIDTH];
   char vertmp[128];
-  sprintf(vertmp, "CMake Version %s", cmVersion::GetCMakeVersion());
+  snprintf(vertmp, sizeof(vertmp), "CMake Version %s",
+           cmVersion::GetCMakeVersion());
   size_t sideSpace = (width - strlen(vertmp));
   for (size_t i = 0; i < sideSpace; i++) {
     version[i] = ' ';
@@ -105,7 +106,7 @@ void cmCursesLongMessageForm::PrintKeys()
     return;
   }
   char firstLine[512];
-  sprintf(firstLine, "Press [e] to exit screen");
+  snprintf(firstLine, sizeof(firstLine), "Press [e] to exit screen");
 
   char fmt_s[] = "%s";
   curses_move(y - 2, 0);
@@ -176,7 +177,8 @@ void cmCursesLongMessageForm::HandleInput()
     this->PrintKeys();
     int key = getch();
 
-    sprintf(debugMessage, "Message widget handling input, key: %d", key);
+    snprintf(debugMessage, sizeof(debugMessage),
+             "Message widget handling input, key: %d", key);
     cmCursesForm::LogMessage(debugMessage);
 
     // quit

+ 14 - 12
Source/CursesDialog/cmCursesMainForm.cxx

@@ -322,22 +322,22 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
       memset(thirdLine, ' ', 68);
     } else {
       if (this->OkToGenerate) {
-        sprintf(firstLine,
-                "      [l] Show log output   [c] Configure"
-                "       [g] Generate        ");
+        snprintf(firstLine, sizeof(firstLine),
+                 "      [l] Show log output   [c] Configure"
+                 "       [g] Generate        ");
       } else {
-        sprintf(firstLine,
-                "      [l] Show log output   [c] Configure"
-                "                           ");
+        snprintf(firstLine, sizeof(firstLine),
+                 "      [l] Show log output   [c] Configure"
+                 "                           ");
       }
       {
         const char* toggleKeyInstruction =
           "      [t] Toggle advanced mode (currently %s)";
-        sprintf(thirdLine, toggleKeyInstruction,
-                this->AdvancedMode ? "on" : "off");
+        snprintf(thirdLine, sizeof(thirdLine), toggleKeyInstruction,
+                 this->AdvancedMode ? "on" : "off");
       }
-      sprintf(secondLine,
-              "      [h] Help              [q] Quit without generating");
+      snprintf(secondLine, sizeof(secondLine),
+               "      [h] Help              [q] Quit without generating");
     }
 
     curses_move(y - 4, 0);
@@ -356,7 +356,8 @@ void cmCursesMainForm::PrintKeys(int process /* = 0 */)
 
   if (cw) {
     char pageLine[512] = "";
-    sprintf(pageLine, "Page %d of %d", cw->GetPage(), this->NumberOfPages);
+    snprintf(pageLine, sizeof(pageLine), "Page %d of %d", cw->GetPage(),
+             this->NumberOfPages);
     curses_move(0, 65 - static_cast<unsigned int>(strlen(pageLine)) - 1);
     printw(fmt_s, pageLine);
   }
@@ -739,7 +740,8 @@ void cmCursesMainForm::HandleInput()
     if ((!currentWidget || !widgetHandled) && !this->SearchMode) {
       // If the current widget does not want to handle input,
       // we handle it.
-      sprintf(debugMessage, "Main form handling input, key: %d", key);
+      snprintf(debugMessage, sizeof(debugMessage),
+               "Main form handling input, key: %d", key);
       cmCursesForm::LogMessage(debugMessage);
       // quit
       if (key == 'q') {

+ 2 - 1
Source/CursesDialog/cmCursesStringWidget.cxx

@@ -85,7 +85,8 @@ bool cmCursesStringWidget::HandleInput(int& key, cmCursesMainForm* fm,
 
   // <Enter> is used to change edit mode (like <Esc> in vi).
   while (!this->Done) {
-    sprintf(debugMessage, "String widget handling input, key: %d", key);
+    snprintf(debugMessage, sizeof(debugMessage),
+             "String widget handling input, key: %d", key);
     cmCursesForm::LogMessage(debugMessage);
 
     fm->PrintKeys();

+ 8 - 7
Source/cmCTest.cxx

@@ -227,8 +227,8 @@ struct tm* cmCTest::GetNightlyTime(std::string const& str, bool tomorrowtag)
   char buf[1024];
   // add todays year day and month to the time in str because
   // curl_getdate no longer assumes the day is today
-  sprintf(buf, "%d%02d%02d %s", lctime->tm_year + 1900, lctime->tm_mon + 1,
-          lctime->tm_mday, str.c_str());
+  snprintf(buf, sizeof(buf), "%d%02d%02d %s", lctime->tm_year + 1900,
+           lctime->tm_mon + 1, lctime->tm_mday, str.c_str());
   cmCTestLog(this, OUTPUT,
              "Determine Nightly Start Time" << std::endl
                                             << "   Specified time: " << str
@@ -543,9 +543,9 @@ int cmCTest::Initialize(const char* binary_dir, cmCTestStartCommand* command)
             this->Impl->TomorrowTag);
         }
         char datestring[100];
-        sprintf(datestring, "%04d%02d%02d-%02d%02d", lctime->tm_year + 1900,
-                lctime->tm_mon + 1, lctime->tm_mday, lctime->tm_hour,
-                lctime->tm_min);
+        snprintf(datestring, sizeof(datestring), "%04d%02d%02d-%02d%02d",
+                 lctime->tm_year + 1900, lctime->tm_mon + 1, lctime->tm_mday,
+                 lctime->tm_hour, lctime->tm_min);
         tag = datestring;
         cmsys::ofstream ofs(tagfile.c_str());
         if (ofs) {
@@ -2967,8 +2967,9 @@ void cmCTest::SetStopTime(std::string const& time_str)
 
   tzone_offset *= 100;
   char buf[1024];
-  sprintf(buf, "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
-          lctime->tm_mon + 1, lctime->tm_mday, time_str.c_str(), tzone_offset);
+  snprintf(buf, sizeof(buf), "%d%02d%02d %s %+05i", lctime->tm_year + 1900,
+           lctime->tm_mon + 1, lctime->tm_mday, time_str.c_str(),
+           tzone_offset);
 
   time_t stop_time = curl_getdate(buf, &current_time);
   if (stop_time == -1) {

+ 2 - 1
Source/cmCoreTryCompile.cxx

@@ -699,7 +699,8 @@ int cmCoreTryCompile::TryCompileCode(std::vector<std::string> const& argv,
 
     /* Use a random file name to avoid rapid creation and deletion
        of the same executable name (some filesystems fail on that).  */
-    sprintf(targetNameBuf, "cmTC_%05x", cmSystemTools::RandomSeed() & 0xFFFFF);
+    snprintf(targetNameBuf, sizeof(targetNameBuf), "cmTC_%05x",
+             cmSystemTools::RandomSeed() & 0xFFFFF);
     targetName = targetNameBuf;
 
     if (!targets.empty()) {

+ 1 - 1
Source/cmExecProgramCommand.cxx

@@ -114,7 +114,7 @@ bool cmExecProgramCommand(std::vector<std::string> const& args,
 
   if (!return_variable.empty()) {
     char buffer[100];
-    sprintf(buffer, "%d", retVal);
+    snprintf(buffer, sizeof(buffer), "%d", retVal);
     status.GetMakefile().AddDefinition(return_variable, buffer);
   }
 

+ 2 - 2
Source/cmExecuteProcessCommand.cxx

@@ -318,7 +318,7 @@ bool cmExecuteProcessCommand(std::vector<std::string> const& args,
       case cmsysProcess_State_Exited: {
         int v = cmsysProcess_GetExitValue(cp);
         char buf[16];
-        sprintf(buf, "%d", v);
+        snprintf(buf, sizeof(buf), "%d", v);
         status.GetMakefile().AddDefinition(arguments.ResultVariable, buf);
       } break;
       case cmsysProcess_State_Exception:
@@ -346,7 +346,7 @@ bool cmExecuteProcessCommand(std::vector<std::string> const& args,
               int exitCode =
                 cmsysProcess_GetExitValueByIndex(cp, static_cast<int>(i));
               char buf[16];
-              sprintf(buf, "%d", exitCode);
+              snprintf(buf, sizeof(buf), "%d", exitCode);
               res.emplace_back(buf);
             } break;
             case kwsysProcess_StateByIndex_Exception:

+ 4 - 3
Source/cmFileCommand.cxx

@@ -217,7 +217,7 @@ bool HandleReadCommand(std::vector<std::string> const& args,
     char c;
     while ((sizeLimit != 0) && (file.get(c))) {
       char hex[4];
-      sprintf(hex, "%.2x", c & 0xff);
+      snprintf(hex, sizeof(hex), "%.2x", c & 0xff);
       output += hex;
       if (sizeLimit > 0) {
         sizeLimit--;
@@ -1627,8 +1627,9 @@ size_t cmFileCommandCurlDebugCallback(CURL*, curl_infotype type, char* chPtr,
     case CURLINFO_SSL_DATA_IN:
     case CURLINFO_SSL_DATA_OUT: {
       char buf[128];
-      int n = sprintf(buf, "[%" KWIML_INT_PRIu64 " bytes data]\n",
-                      static_cast<KWIML_INT_uint64_t>(size));
+      int n =
+        snprintf(buf, sizeof(buf), "[%" KWIML_INT_PRIu64 " bytes data]\n",
+                 static_cast<KWIML_INT_uint64_t>(size));
       if (n > 0) {
         cm::append(vec, buf, buf + n);
       }

+ 1 - 1
Source/cmFindPackageCommand.cxx

@@ -671,7 +671,7 @@ void cmFindPackageCommand::SetVersionVariables(
   addDefinition(prefix, version);
 
   char buf[64];
-  sprintf(buf, "%u", major);
+  snprintf(buf, sizeof(buf), "%u", major);
   addDefinition(prefix + "_MAJOR", buf);
   sprintf(buf, "%u", minor);
   addDefinition(prefix + "_MINOR", buf);

+ 2 - 1
Source/cmGeneratedFileStream.cxx

@@ -136,7 +136,8 @@ void cmGeneratedFileStreamBase::Open(std::string const& name)
     this->TempName += this->TempExt;
   } else {
     char buf[64];
-    sprintf(buf, "tmp%05x", cmSystemTools::RandomSeed() & 0xFFFFF);
+    snprintf(buf, sizeof(buf), "tmp%05x",
+             cmSystemTools::RandomSeed() & 0xFFFFF);
     this->TempName += buf;
   }
 

+ 1 - 1
Source/cmGlobalGenerator.cxx

@@ -1311,7 +1311,7 @@ void cmGlobalGenerator::Configure()
   // update the cache entry for the number of local generators, this is used
   // for progress
   char num[100];
-  sprintf(num, "%d", static_cast<int>(this->Makefiles.size()));
+  snprintf(num, sizeof(num), "%d", static_cast<int>(this->Makefiles.size()));
   this->GetCMakeInstance()->AddCacheEntry("CMAKE_NUMBER_OF_MAKEFILES", num,
                                           "number of local generators",
                                           cmStateEnums::INTERNAL);

+ 1 - 1
Source/cmGlobalNinjaGenerator.cxx

@@ -156,7 +156,7 @@ std::string cmGlobalNinjaGenerator::EncodeRuleName(std::string const& name)
       encoded += i;
     } else {
       char buf[16];
-      sprintf(buf, ".%02x", static_cast<unsigned int>(i));
+      snprintf(buf, sizeof(buf), ".%02x", static_cast<unsigned int>(i));
       encoded += buf;
     }
   }

+ 1 - 1
Source/cmListCommand.cxx

@@ -155,7 +155,7 @@ bool HandleLengthCommand(std::vector<std::string> const& args,
   GetList(varArgsExpanded, listName, status.GetMakefile());
   size_t length = varArgsExpanded.size();
   char buffer[1024];
-  sprintf(buffer, "%d", static_cast<int>(length));
+  snprintf(buffer, sizeof(buffer), "%d", static_cast<int>(length));
 
   status.GetMakefile().AddDefinition(variableName, buffer);
   return true;

+ 2 - 2
Source/cmLocalGenerator.cxx

@@ -3505,7 +3505,7 @@ std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
       bool done;
       int cc = 0;
       char rpstr[100];
-      sprintf(rpstr, "_p_");
+      snprintf(rpstr, sizeof(rpstr), "_p_");
       cmSystemTools::ReplaceString(ssin, "+", rpstr);
       std::string sssin = sin;
       do {
@@ -3521,7 +3521,7 @@ std::string& cmLocalGenerator::CreateSafeUniqueObjectFileName(
         }
         sssin = ssin;
         cmSystemTools::ReplaceString(ssin, "_p_", rpstr);
-        sprintf(rpstr, "_p%d_", cc++);
+        snprintf(rpstr, sizeof(rpstr), "_p%d_", cc++);
       } while (!done);
     }
 

+ 3 - 3
Source/cmLocalUnixMakefileGenerator3.cxx

@@ -1279,7 +1279,7 @@ std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
     // it is used then add number to the end of the variable
     while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
       ++ni;
-      sprintf(buffer, "%04d", ni);
+      snprintf(buffer, sizeof(buffer), "%04d", ni);
       ret = unmodified + buffer;
     }
     this->ShortMakeVariableMap[ret] = "1";
@@ -1304,11 +1304,11 @@ std::string cmLocalUnixMakefileGenerator3::CreateMakeVariable(
     }
     char buffer[5];
     int ni = 0;
-    sprintf(buffer, "%04d", ni);
+    snprintf(buffer, sizeof(buffer), "%04d", ni);
     ret = str1 + str2 + buffer;
     while (this->ShortMakeVariableMap.count(ret) && ni < 1000) {
       ++ni;
-      sprintf(buffer, "%04d", ni);
+      snprintf(buffer, sizeof(buffer), "%04d", ni);
       ret = str1 + str2 + buffer;
     }
     if (ni == 1000) {

+ 1 - 1
Source/cmMacroCommand.cxx

@@ -77,7 +77,7 @@ bool cmMacroHelperCommand::operator()(
   argVs.reserve(expandedArgs.size());
   char argvName[60];
   for (unsigned int j = 0; j < expandedArgs.size(); ++j) {
-    sprintf(argvName, "${ARGV%u}", j);
+    snprintf(argvName, sizeof(argvName), "${ARGV%u}", j);
     argVs.emplace_back(argvName);
   }
   // Invoke all the functions that were collected in the block.

+ 2 - 2
Source/cmMakefile.cxx

@@ -134,8 +134,8 @@ cmDirectoryId cmMakefile::GetDirectoryId() const
   // If we ever need to expose this to CMake language code we should
   // add a read-only property in cmMakefile::GetProperty.
   char buf[32];
-  sprintf(buf, "(%p)",
-          static_cast<void const*>(this)); // cast avoids format warning
+  snprintf(buf, sizeof(buf), "(%p)",
+           static_cast<void const*>(this)); // cast avoids format warning
   return std::string(buf);
 }
 

+ 1 - 1
Source/cmMakefileTargetGenerator.cxx

@@ -2176,7 +2176,7 @@ void cmMakefileTargetGenerator::CreateObjectLists(
     for (unsigned int i = 0; i < object_strings.size(); ++i) {
       // Number the response files.
       char rsp[32];
-      sprintf(rsp, "objects%u.rsp", i + 1);
+      snprintf(rsp, sizeof(rsp), "objects%u.rsp", i + 1);
 
       // Create this response file.
       std::string objects_rsp =

+ 1 - 1
Source/cmMathCommand.cxx

@@ -107,7 +107,7 @@ bool HandleExprCommand(std::vector<std::string> const& args,
       fmt = "%" KWIML_INT_PRId64;
       break;
   }
-  sprintf(buffer, fmt, helper.GetResult());
+  snprintf(buffer, sizeof(buffer), fmt, helper.GetResult());
 
   std::string const& w = helper.GetWarning();
   if (!w.empty()) {

+ 4 - 3
Source/cmProjectCommand.cxx

@@ -235,14 +235,15 @@ bool cmProjectCommand(std::vector<std::string> const& args,
     std::array<std::string, MAX_VERSION_COMPONENTS> version_components;
 
     if (cmp0096 == cmPolicies::OLD || cmp0096 == cmPolicies::WARN) {
-      char vb[MAX_VERSION_COMPONENTS]
-             [std::numeric_limits<unsigned>::digits10 + 2];
+      constexpr size_t maxIntLength =
+        std::numeric_limits<unsigned>::digits10 + 2;
+      char vb[MAX_VERSION_COMPONENTS][maxIntLength];
       unsigned v[MAX_VERSION_COMPONENTS] = { 0, 0, 0, 0 };
       const int vc = std::sscanf(version.c_str(), "%u.%u.%u.%u", &v[0], &v[1],
                                  &v[2], &v[3]);
       for (auto i = 0u; i < MAX_VERSION_COMPONENTS; ++i) {
         if (int(i) < vc) {
-          std::sprintf(vb[i], "%u", v[i]);
+          std::snprintf(vb[i], maxIntLength, "%u", v[i]);
           version_string += &"."[std::size_t(i == 0)];
           version_string += vb[i];
           version_components[i] = vb[i];

+ 1 - 1
Source/cmStringCommand.cxx

@@ -526,7 +526,7 @@ bool HandleLengthCommand(std::vector<std::string> const& args,
 
   size_t length = stringValue.size();
   char buffer[1024];
-  sprintf(buffer, "%d", static_cast<int>(length));
+  snprintf(buffer, sizeof(buffer), "%d", static_cast<int>(length));
 
   status.GetMakefile().AddDefinition(variableName, buffer);
   return true;

+ 8 - 6
Source/cmSystemTools.cxx

@@ -1693,7 +1693,8 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
   /* Use uname if it's present, else uid. */
   p = archive_entry_uname(entry);
   if ((p == nullptr) || (*p == '\0')) {
-    sprintf(tmp, "%lu ", static_cast<unsigned long>(archive_entry_uid(entry)));
+    snprintf(tmp, sizeof(tmp), "%lu ",
+             static_cast<unsigned long>(archive_entry_uid(entry)));
     p = tmp;
   }
   w = strlen(p);
@@ -1707,7 +1708,8 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
     fprintf(out, "%s", p);
     w = strlen(p);
   } else {
-    sprintf(tmp, "%lu", static_cast<unsigned long>(archive_entry_gid(entry)));
+    snprintf(tmp, sizeof(tmp), "%lu",
+             static_cast<unsigned long>(archive_entry_gid(entry)));
     w = strlen(tmp);
     fprintf(out, "%s", tmp);
   }
@@ -1721,15 +1723,15 @@ void list_item_verbose(FILE* out, struct archive_entry* entry)
       archive_entry_filetype(entry) == AE_IFBLK) {
     unsigned long rdevmajor = archive_entry_rdevmajor(entry);
     unsigned long rdevminor = archive_entry_rdevminor(entry);
-    sprintf(tmp, "%lu,%lu", rdevmajor, rdevminor);
+    snprintf(tmp, sizeof(tmp), "%lu,%lu", rdevmajor, rdevminor);
   } else {
     /*
      * Note the use of platform-dependent macros to format
      * the filesize here.  We need the format string and the
      * corresponding type for the cast.
      */
-    sprintf(tmp, BSDTAR_FILESIZE_PRINTF,
-            static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
+    snprintf(tmp, sizeof(tmp), BSDTAR_FILESIZE_PRINTF,
+             static_cast<BSDTAR_FILESIZE_TYPE>(archive_entry_size(entry)));
   }
   if (w + strlen(tmp) >= gs_width) {
     gs_width = w + strlen(tmp) + 1;
@@ -3289,7 +3291,7 @@ std::string cmSystemTools::EncodeURL(std::string const& in, bool escapeSlashes)
       case ' ':
       case '=':
       case '%':
-        sprintf(hexCh, "%%%02X", static_cast<int>(c));
+        snprintf(hexCh, sizeof(hexCh), "%%%02X", static_cast<int>(c));
         break;
       case '/':
         if (escapeSlashes) {

+ 1 - 1
Source/cmTryRunCommand.cxx

@@ -211,7 +211,7 @@ void cmTryRunCommand::RunExecutable(const std::string& runArgs,
   char retChar[16];
   const char* retStr;
   if (worked) {
-    sprintf(retChar, "%i", retVal);
+    snprintf(retChar, sizeof(retChar), "%i", retVal);
     retStr = retChar;
   } else {
     retStr = "FAILED_TO_RUN";

+ 2 - 2
Source/cmXMLSafe.cxx

@@ -73,7 +73,7 @@ std::ostream& operator<<(std::ostream& os, cmXMLSafe const& self)
       } else {
         // Use a human-readable hex value for this invalid character.
         char buf[16];
-        sprintf(buf, "%X", ch);
+        snprintf(buf, sizeof(buf), "%X", ch);
         os << "[NON-XML-CHAR-0x" << buf << "]";
       }
 
@@ -82,7 +82,7 @@ std::ostream& operator<<(std::ostream& os, cmXMLSafe const& self)
       ch = static_cast<unsigned char>(*first++);
       // Use a human-readable hex value for this invalid byte.
       char buf[16];
-      sprintf(buf, "%X", ch);
+      snprintf(buf, sizeof(buf), "%X", ch);
       os << "[NON-UTF-8-BYTE-0x" << buf << "]";
     }
   }

+ 3 - 2
Tests/BundleTest/BundleLib.cxx

@@ -20,7 +20,8 @@ int findBundleFile(char* exec, const char* file)
 {
   int res;
   char* nexec = strdup(exec);
-  char* fpath = (char*)malloc(strlen(exec) + 100);
+  size_t fpathlen = strlen(nexec) + 1 + strlen(file);
+  char* fpath = (char*)malloc(fpathlen);
   int cc;
   int cnt = 0;
   printf("Process executable name: %s\n", exec);
@@ -36,7 +37,7 @@ int findBundleFile(char* exec, const char* file)
     }
   }
   printf("Process executable path: %s\n", nexec);
-  sprintf(fpath, "%s/%s", nexec, file);
+  snprintf(fpath, fpathlen, "%s/%s", nexec, file);
   printf("Check for file: %s\n", fpath);
   res = fileExists(fpath);
   free(nexec);