util: Fix incorrect iteration over entries in InMemoryStorage

Change-Id: I975b1160570ccf6f1d9f46b0e04bc6f5d04b4675
Refs: #2301, #2149
diff --git a/src/util/in-memory-storage.cpp b/src/util/in-memory-storage.cpp
index d294dd6..9c3146f 100644
--- a/src/util/in-memory-storage.cpp
+++ b/src/util/in-memory-storage.cpp
@@ -104,8 +104,7 @@
   // evict all items from cache
   Cache::iterator it = m_cache.begin();
   while (it != m_cache.end()) {
-    freeEntry(it);
-    it++;
+    it = freeEntry(it);
   }
 
   BOOST_ASSERT(m_freeEntries.size() == m_capacity);
@@ -319,13 +318,14 @@
   return 0;
 }
 
-void
-InMemoryStorage::freeEntry(Cache::index<byFullName>::type::iterator it) {
+InMemoryStorage::Cache::iterator
+InMemoryStorage::freeEntry(Cache::iterator it)
+{
   //push the *empty* entry into mem pool
   (*it)->release();
   m_freeEntries.push(*it);
   m_nPackets--;
-  m_cache.get<byFullName>().erase(it);
+  return m_cache.erase(it);
 }
 
 void
@@ -334,14 +334,10 @@
   if (isPrefix) {
     Cache::index<byFullName>::type::iterator it = m_cache.get<byFullName>().lower_bound(prefix);
 
-    if (it == m_cache.get<byFullName>().end())
-      return;
-
     while (it != m_cache.get<byFullName>().end() && prefix.isPrefixOf((*it)->getName())) {
       //let derived class do something with the entry
       beforeErase(*it);
-      freeEntry(it);
-      it++;
+      it = freeEntry(it);
     }
   }
   else {
diff --git a/src/util/in-memory-storage.hpp b/src/util/in-memory-storage.hpp
index b9fb9da..9bec775 100644
--- a/src/util/in-memory-storage.hpp
+++ b/src/util/in-memory-storage.hpp
@@ -270,9 +270,10 @@
 
 NDN_CXX_PUBLIC_WITH_TESTS_ELSE_PRIVATE:
   /** @brief free in-memory storage entries by an iterator pointing to that entry.
-    */
-  void
-  freeEntry(Cache::index<byFullName>::type::iterator it);
+      @return An iterator pointing to the element that followed the last element erased.
+   */
+  Cache::iterator
+  freeEntry(Cache::iterator it);
 
   /** @brief Implements child selector (leftmost, rightmost, undeclared).
    *  Operates on the first layer of a skip list.