Fix main space memory leak and add checks.

The hypothesis is that we were leaking the main space and its
bitmaps, then eventually we would run out of virtual address space,
which would cause a null bitmap (DCHECK). Finally when we tried
adding the space with a null bitmap to the heap bitmap it segfaulted.

Changed some non performance critical DCHECK -> CHECK.

Bug: 16563323
Change-Id: I08a1f873752e28ebcf63ebbd90f92d994d7ca96b
diff --git a/runtime/gc/heap.cc b/runtime/gc/heap.cc
index 33ff3bb..1d80833 100644
--- a/runtime/gc/heap.cc
+++ b/runtime/gc/heap.cc
@@ -692,7 +692,7 @@
     accounting::ContinuousSpaceBitmap* live_bitmap = continuous_space->GetLiveBitmap();
     accounting::ContinuousSpaceBitmap* mark_bitmap = continuous_space->GetMarkBitmap();
     if (live_bitmap != nullptr) {
-      DCHECK(mark_bitmap != nullptr);
+      CHECK(mark_bitmap != nullptr);
       live_bitmap_->AddContinuousSpaceBitmap(live_bitmap);
       mark_bitmap_->AddContinuousSpaceBitmap(mark_bitmap);
     }
@@ -703,7 +703,7 @@
       return a->Begin() < b->Begin();
     });
   } else {
-    DCHECK(space->IsDiscontinuousSpace());
+    CHECK(space->IsDiscontinuousSpace());
     space::DiscontinuousSpace* discontinuous_space = space->AsDiscontinuousSpace();
     live_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetLiveBitmap());
     mark_bitmap_->AddLargeObjectBitmap(discontinuous_space->GetMarkBitmap());
@@ -1595,19 +1595,20 @@
         Compact(bump_pointer_space_, main_space_, kGcCauseCollectorTransition);
         // Use the now empty main space mem map for the bump pointer temp space.
         mem_map.reset(main_space_->ReleaseMemMap());
-        // Remove the main space so that we don't try to trim it, this doens't work for debug
-        // builds since RosAlloc attempts to read the magic number from a protected page.
-        RemoveSpace(main_space_);
         // Unset the pointers just in case.
         if (dlmalloc_space_ == main_space_) {
           dlmalloc_space_ = nullptr;
         } else if (rosalloc_space_ == main_space_) {
           rosalloc_space_ = nullptr;
         }
+        // Remove the main space so that we don't try to trim it, this doens't work for debug
+        // builds since RosAlloc attempts to read the magic number from a protected page.
+        RemoveSpace(main_space_);
         RemoveRememberedSet(main_space_);
-        RemoveRememberedSet(main_space_backup_.get());
-        main_space_backup_.reset(nullptr);
+        delete main_space_;  // Delete the space since it has been removed.
         main_space_ = nullptr;
+        RemoveRememberedSet(main_space_backup_.get());
+        main_space_backup_.reset(nullptr);  // Deletes the space.
         temp_space_ = space::BumpPointerSpace::CreateFromMemMap("Bump pointer space 2",
                                                                 mem_map.release());
         AddSpace(temp_space_);