[nnkit] Throw bad_alloc on malloc failure (#1624)
author박종현/동작제어Lab(SR)/Staff Engineer/삼성전자 <jh1302.park@samsung.com>
Fri, 21 Sep 2018 07:42:10 +0000 (16:42 +0900)
committerGitHub Enterprise <noreply-CODE@samsung.com>
Fri, 21 Sep 2018 07:42:10 +0000 (16:42 +0900)
tflite backend (for nnsuite conv case) internally uses typed_malloc
method, which wraps std::malloc, which may return nullptr on memory
allocation failure.

This commit revises this method to throw std::bad_alloc on memory
allocation failure (similarly as C++ new) to make it easy to detect
memory allocation failure.

Signed-off-by: Jonghyun Park <jh1302.park@samsung.com>
contrib/nnkit/contrib/nnsuite/conv/tflite/ConvBackend.cpp

index 0662f77..01a7496 100644 (file)
 #include <tensorflow/contrib/lite/builtin_op_data.h>
 
 #include <cstdlib>
+#include <stdexcept>
 
 using namespace ::tflite;
 using namespace ::tflite::ops::builtin;
 
+/**
+ * @brief Allocate memory with malloc and return a typed pointer
+ *
+ * NOTE This function throws std::bac_alloc exception on allocation failure
+ */
 template<typename T> T *typed_malloc(void)
 {
-  return reinterpret_cast<T *>(malloc(sizeof(T)));
+  if (auto res = reinterpret_cast<T *>(malloc(sizeof(T))))
+  {
+    return res;
+  }
+  throw std::bad_alloc{};
 }
 
 // Comment from 'context.h'