You should refactor this code such that you do not recreate matrices and solvers inside loops, as petsc has changed its garbage collection.