From 8349b4fbc7577d887565865242083835692befb7 Mon Sep 17 00:00:00 2001
From: Jonathan Youett <youett@mi.fu-berlin.de>
Date: Wed, 29 Oct 2014 12:35:38 +0100
Subject: [PATCH] [bugfix] Fixes assignment of BCRSMatrix with nonmatching
 number of rows.

When assigning a BCRSMatrix to another BCRSMatrix which was setup for
a different size/pattern, it segfaulted and I got the following
Exception:

"InvalidStateException [allocate:.../dune/istl/bcrsmatrix.hh:2108]:
Rows have already been allocated, cannot allocate a second time."

The problem was, that inside the assignment operator the rows (r) were
never deallocated. This commit fixes this and adds a testcase.

Testcase slightly modified by Markus.
---
 COPYING                          |  2 +-
 dune/istl/bcrsmatrix.hh          |  3 ++-
 dune/istl/test/bcrsassigntest.cc | 46 ++++++++++++++++++++++++++++++++
 3 files changed, 49 insertions(+), 2 deletions(-)
 create mode 100644 dune/istl/test/bcrsassigntest.cc

diff --git a/COPYING b/COPYING
index 9d27ece58..ca88c0bab 100644
--- a/COPYING
+++ b/COPYING
@@ -30,7 +30,7 @@ Copyright holders:
 2013          BÃ¥rd Skaflestad
 2006--2010    Martin Weiser
 2011--2012    Matthias Wohlmuth
-
+2014          Jonathan Youett
 
 The DUNE library and headers are licensed under version 2 of the GNU
 General Public License (see below), with a special exception for
diff --git a/dune/istl/bcrsmatrix.hh b/dune/istl/bcrsmatrix.hh
index baea1b357..b5c1fb857 100644
--- a/dune/istl/bcrsmatrix.hh
+++ b/dune/istl/bcrsmatrix.hh
@@ -875,7 +875,8 @@ namespace Dune {
         DUNE_THROW(InvalidStateException,"BCRSMatrix can only be copied when both target and source are empty or fully built)");
 
       // make it simple: ALWAYS throw away memory for a and j
-      deallocate(false);
+      // and deallocate rows only if n != Mat.n
+      deallocate(n!=Mat.n);
 
       // reallocate the rows if required
       if (n>0 && n!=Mat.n) {
diff --git a/dune/istl/test/bcrsassigntest.cc b/dune/istl/test/bcrsassigntest.cc
new file mode 100644
index 000000000..f52661703
--- /dev/null
+++ b/dune/istl/test/bcrsassigntest.cc
@@ -0,0 +1,46 @@
+#include <config.h>
+
+#include <dune/istl/bcrsmatrix.hh>
+
+using namespace Dune;
+
+int main (int argc, char** argv)
+{
+    try
+    {
+        typedef BCRSMatrix<FieldMatrix<double,2,2> >  Mat;
+
+        Mat A(1,1, Mat::random);
+
+        A.setrowsize(0,1);
+
+        A.endrowsizes();
+
+        A.addindex(0, 0);
+
+        A.endindices();
+        A = 0;
+
+        Mat B(2,2, Mat::random);
+
+        B.setrowsize(0,2);
+        B.setrowsize(1,1);
+
+        B.endrowsizes();
+
+        B.addindex(0, 0);
+        B.addindex(0, 1);
+
+        B.addindex(1, 1);
+
+        B.endindices();
+        B = 0;
+
+        B  = A;
+
+    } catch(Exception e){
+        std::cout<<e<<std::endl;
+        return 1;
+    }
+    return 0;
+}
-- 
GitLab