From e5c23738ed020a50de61d927e572ff05801bda45 Mon Sep 17 00:00:00 2001
From: Jean-Christophe Fillion-Robin <jchris.fillionr@kitware.com>
Date: Thu, 16 Jul 2015 14:44:43 -0400
Subject: [PATCH] SystemTools: Fix DetectFileType failure on missing file

Fix the following error reported by valgrind memcheck tool:

==31549== 256 bytes in 1 blocks are definitely lost in loss record 1 of 1
==31549==    at 0x4C2B800: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==31549==    by 0x44F3AA: kwsys::SystemTools::DetectFileType(char const*, unsigned long, double) (in .../kwsysTestsCxx)
==31549==    by 0x43D75E: CheckFileOperations() (in .../kwsysTestsCxx)
==31549==    by 0x43FAC5: testSystemTools(int, char**) (in .../kwsysTestsCxx)
==31549==    by 0x434A2B: main (in .../kwsysTestsCxx)

Change-Id: I42db9774bf30889b67921a538e00c1bf519a2719
---
 SystemTools.cxx     |  1 +
 testSystemTools.cxx | 11 +++++++++++
 2 files changed, 12 insertions(+)

diff --git a/SystemTools.cxx b/SystemTools.cxx
index 34522594..a2c24a7d 100644
--- a/SystemTools.cxx
+++ b/SystemTools.cxx
@@ -4243,6 +4243,7 @@ SystemTools::DetectFileType(const char *filename,
   fclose(fp);
   if (read_length == 0)
     {
+    delete [] buffer;
     return SystemTools::FileTypeUnknown;
     }
 
diff --git a/testSystemTools.cxx b/testSystemTools.cxx
index 15d8eab1..67a90fa2 100644
--- a/testSystemTools.cxx
+++ b/testSystemTools.cxx
@@ -98,6 +98,8 @@ static bool CheckEscapeChars(kwsys_stl::string input,
 static bool CheckFileOperations()
 {
   bool res = true;
+  const kwsys_stl::string testNonExistingFile(TEST_SYSTEMTOOLS_SOURCE_DIR
+    "/testSystemToolsNonExistingFile");
   const kwsys_stl::string testBinFile(TEST_SYSTEMTOOLS_SOURCE_DIR
     "/testSystemTools.bin");
   const kwsys_stl::string testTxtFile(TEST_SYSTEMTOOLS_SOURCE_DIR
@@ -106,6 +108,15 @@ static bool CheckFileOperations()
     "/testSystemToolsNewDir");
   const kwsys_stl::string testNewFile(testNewDir + "/testNewFile.txt");
 
+  if (kwsys::SystemTools::DetectFileType(testNonExistingFile.c_str()) !=
+      kwsys::SystemTools::FileTypeUnknown)
+    {
+    kwsys_ios::cerr
+      << "Problem with DetectFileType - failed to detect type of: "
+      << testNonExistingFile << kwsys_ios::endl;
+    res = false;
+    }
+
   if (kwsys::SystemTools::DetectFileType(testBinFile.c_str()) !=
       kwsys::SystemTools::FileTypeBinary)
     {
-- 
GitLab