diff --git a/src/core/coap/coap.cpp b/src/core/coap/coap.cpp index 94a182162..150332d53 100644 --- a/src/core/coap/coap.cpp +++ b/src/core/coap/coap.cpp @@ -746,18 +746,21 @@ exit: void ResponsesQueue::EnqueueResponse(Message &aMessage, const Ip6::MessageInfo &aMessageInfo) { - Message * copy; + otError error = OT_ERROR_NONE; + Message * cachedResponse = NULL; + Message * responseCopy = NULL; EnqueuedResponseHeader enqueuedResponseHeader(aMessageInfo); uint16_t messageCount; uint16_t bufferCount; - switch (GetMatchedResponseCopy(aMessage, aMessageInfo, ©)) + switch (GetMatchedResponseCopy(aMessage, aMessageInfo, &cachedResponse)) { case OT_ERROR_NOT_FOUND: break; case OT_ERROR_NONE: - copy->Free(); + assert(cachedResponse != NULL); + cachedResponse->Free(); // fall through @@ -773,10 +776,10 @@ void ResponsesQueue::EnqueueResponse(Message &aMessage, const Ip6::MessageInfo & DequeueOldestResponse(); } - VerifyOrExit((copy = aMessage.Clone()) != NULL); + VerifyOrExit((responseCopy = aMessage.Clone()) != NULL); - enqueuedResponseHeader.AppendTo(*copy); - mQueue.Enqueue(*copy); + SuccessOrExit(error = enqueuedResponseHeader.AppendTo(*responseCopy)); + mQueue.Enqueue(*responseCopy); if (!mTimer.IsRunning()) { @@ -784,6 +787,12 @@ void ResponsesQueue::EnqueueResponse(Message &aMessage, const Ip6::MessageInfo & } exit: + + if (error != OT_ERROR_NONE && responseCopy != NULL) + { + responseCopy->Free(); + } + return; }