[petsc-users] Inquiry about the c++ destructor and PetscFinalize.

Constantine Khrulev ckhroulev at alaska.edu
Fri Jun 16 17:52:46 CDT 2023


In your code the destructor of DMManage is called at the end of scope, 
i.e. after the PetscFinalize() call.

You should be able to avoid this error by putting "DMManage objDMManage" 
in a code block to limit its scope and ensure that it is destroyed 
before PETSc is finalized:

int main(int argc, char** argv) {
   PetscFunctionBeginUser;
   PetscCall(PetscInitialize(&argc, &argv, NULL, help));

   {
     DMManage objDMManage;
    } // objDMManage is destroyed here

   PetscFinalize();
   return 0;
}

On 6/16/23 14:13, neil liu wrote:
> Dear Petsc developers,
>
> I am trying to use Petsc with C++. And came across one issue.
> Class DMManage has been defined, one default constructor and 
> destructor has been defined there.
> The code has a runtime error, "double free or corruption". Finally I 
> found that, this is due to PetscFinalize. If I called explicitly the 
> destructor before this PetscFinalze, the error will disappear.
>
> Does that mean PetscFinalize do some work to destroy DM?
>
> Thanks,
>
> #include <petscdmplex.h>
> #include <petscdmadaptor.h>
> #include <petscds.h>
> #include <petscviewerhdf5.h>
>
> class DMManage{
>   PetscSF distributionSF;
> public:
>   DM dm;
>   DMManage();
>   ~DMManage();
> };
>
> DMManage::DMManage(){
>   const char filename[] = "ParallelWaveguide.msh";
>   DM dmDist;
>   PetscViewer viewer;
>   PetscViewerCreate(PETSC_COMM_WORLD, &viewer);
>   PetscViewerSetType(viewer, PETSCVIEWERASCII);
>   PetscViewerFileSetMode(viewer, FILE_MODE_READ);
>   PetscViewerFileSetName(viewer, filename);
>   DMPlexCreateGmsh(PETSC_COMM_WORLD, viewer, PETSC_TRUE, &dm);
>   PetscViewerDestroy(&viewer);
>   PetscInt overlap = 0;
>   DMPlexDistribute(dm, overlap, &distributionSF, &dmDist);
>   std::cout<<&dm<<std::endl;
>   if (dmDist) {
>     DMDestroy(&dm);
>     dm = dmDist;
>   }
>   DMDestroy(&dmDist);
> }
>
> DMManage::~DMManage(){
>   DMDestroy(&dm);
> }
>
> int main(int argc, char** argv) {
>   PetscFunctionBeginUser;
>   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
>
>   DMManage objDMManage;
>
>   PetscFinalize();
>   return 0;
> }

-- 
Constantine



More information about the petsc-users mailing list