Prevent from dereferencing nullptr returned by localtime() 78/130678/7
authorPiotr Sawicki <p.sawicki2@partner.samsung.com>
Tue, 23 May 2017 09:09:59 +0000 (11:09 +0200)
committerZofia Abramowska <z.abramowska@samsung.com>
Mon, 29 May 2017 13:06:18 +0000 (15:06 +0200)
Change-Id: I4245c0e856c06c7d5e9ad1902590f5196f0394e0

src/logger/formatter.cpp

index 4d5cd20..c9fad96 100644 (file)
@@ -32,6 +32,7 @@
 #include <iomanip>
 #include <thread>
 #include <atomic>
+#include <cstring>
 
 namespace logger
 {
@@ -65,14 +66,21 @@ namespace logger
                char time[TIME_COLUMN_LENGTH + 1];
                struct timeval tv;
                gettimeofday(&tv, NULL);
-               struct tm* tm = localtime(&tv.tv_sec);
-               snprintf(time,
-                                sizeof(time),
-                                "%02d:%02d:%02d.%03d",
-                                tm->tm_hour,
-                                tm->tm_min,
-                                tm->tm_sec,
-                                int(tv.tv_usec / 1000));
+               struct tm *localTime = localtime(&tv.tv_sec);
+               if (localTime != nullptr)
+               {
+                       snprintf(time,
+                               sizeof(time),
+                               "%02d:%02d:%02d.%03d",
+                               localTime->tm_hour,
+                               localTime->tm_min,
+                               localTime->tm_sec,
+                               static_cast<int>(tv.tv_usec / 1000));
+               }
+               else
+               {
+                       strncpy(time, "00:00:00.000", sizeof(time));
+               }
 
                return std::string(time);
        }