[nfc] Fixing memory management for messages and records
[platform/core/api/webapi-plugins.git] / src / nfc / nfc_adapter.cc
index 65c87c4..05e0669 100644 (file)
@@ -26,6 +26,7 @@
 #include "common/extension.h"
 #include "common/logger.h"
 #include "common/platform_exception.h"
+#include "common/scope_exit.h"
 #include "common/tools.h"
 #include "nfc/aid_data.h"
 #include "nfc/defs.h"
@@ -1234,15 +1235,15 @@ PlatformResult NFCAdapter::TagTransceive(int tag_id, const picojson::value& args
 PlatformResult NFCAdapter::GetCachedMessage(picojson::object& out) {
   ScopeLogger();
   nfc_ndef_message_h message_handle = NULL;
+  SCOPE_EXIT { NFCMessageUtils::RemoveMessageHandle(message_handle); };
   int result = nfc_manager_get_cached_message(&message_handle);
   if (NFC_ERROR_INVALID_NDEF_MESSAGE == result || NFC_ERROR_NO_NDEF_MESSAGE == result) {
     LoggerE("Error: %d", result);
-    NFCMessageUtils::RemoveMessageHandle(message_handle);
+
     return PlatformResult(ErrorCode::NO_ERROR);
   }
   if (NFC_ERROR_NONE != result) {
     LoggerE("Failed to get cached message: %d", result);
-    NFCMessageUtils::RemoveMessageHandle(message_handle);
     return NFCUtil::CodeToResult(result, "Failed to get cached message");
   }
   unsigned char* raw_data = NULL;
@@ -1250,17 +1251,14 @@ PlatformResult NFCAdapter::GetCachedMessage(picojson::object& out) {
   if (NFC_ERROR_NONE != nfc_ndef_message_get_rawdata(message_handle, &raw_data, &size)) {
     LoggerE("Unknown error while getting message.");
     free(raw_data);
-    NFCMessageUtils::RemoveMessageHandle(message_handle);
     return PlatformResult(ErrorCode::NO_ERROR);
   }
   PlatformResult ret = NFCMessageUtils::ReportNdefMessageFromData(raw_data, size, out);
   free(raw_data);
   if (ret.IsError()) {
     LoggerE("Error: %s", ret.message().c_str());
-    NFCMessageUtils::RemoveMessageHandle(message_handle);
     return ret;
   }
-  NFCMessageUtils::RemoveMessageHandle(message_handle);
   return PlatformResult(ErrorCode::NO_ERROR);
 }