rib: fix use-after-free in Rib::erase and RibManagerFixture::clearRib

Change-Id: Ia4c2211f6c48d852e3b73dc84e298d26ad14f708
Refs: #3787
diff --git a/rib/rib.cpp b/rib/rib.cpp
index 4c4d3c5..eb577bb 100644
--- a/rib/rib.cpp
+++ b/rib/rib.cpp
@@ -1,6 +1,6 @@
 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
 /**
- * Copyright (c) 2014-2015,  Regents of the University of California,
+ * Copyright (c) 2014-2016,  Regents of the University of California,
  *                           Arizona Board of Regents,
  *                           Colorado State University,
  *                           University Pierre & Marie Curie, Sorbonne University,
@@ -162,21 +162,21 @@
 
   // Name prefix exists
   if (ribIt != m_rib.end()) {
-    shared_ptr<RibEntry> entry(ribIt->second);
-
+    shared_ptr<RibEntry> entry = ribIt->second;
     RibEntry::iterator routeIt = entry->findRoute(route);
 
     if (routeIt != entry->end()) {
+      auto faceId = route.faceId;
       entry->eraseRoute(routeIt);
       m_nItems--;
 
       // If this RibEntry no longer has this faceId, unregister from face lookup table
-      if (!entry->hasFaceId(route.faceId)) {
-        m_faceMap[route.faceId].remove(entry);
+      if (!entry->hasFaceId(faceId)) {
+        m_faceMap[faceId].remove(entry);
       }
 
       // If a RibEntry's route list is empty, remove it from the tree
-      if (entry->getRoutes().size() == 0) {
+      if (entry->getRoutes().empty()) {
         eraseEntry(ribIt);
       }
     }
diff --git a/tests/rib/rib-manager.t.cpp b/tests/rib/rib-manager.t.cpp
index 9bd8f72..f3df261 100644
--- a/tests/rib/rib-manager.t.cpp
+++ b/tests/rib/rib-manager.t.cpp
@@ -117,7 +117,7 @@
     };
 
     Name commandPrefix("/localhost/nfd/fib/add-nexthop");
-    for (auto&& command : m_commands) {
+    for (const auto& command : m_commands) {
       if (commandPrefix.isPrefixOf(command.getName())) {
         replyFibAddCommand(command);
         advanceClocks(time::milliseconds(1));
@@ -129,14 +129,11 @@
     m_commands.clear();
   }
 
-  void clearRib()
+  void
+  clearRib()
   {
     while (!m_rib.empty()) {
-      auto& name = m_rib.begin()->first;
-      auto& routes = m_rib.begin()->second->getRoutes();
-      while (!routes.empty()) {
-        m_rib.erase(name, *routes.begin());
-      }
+      m_rib.erase(m_rib.begin()->first, *m_rib.begin()->second->begin());
     }
   }