[petsc-users] Memory corruption with two-dimensional array and PetscMemzero

Jed Brown jed at jedbrown.org
Wed May 14 19:08:21 CDT 2014


Christophe Ortiz <christophe.ortiz at ciemat.es> writes:

> Hi all,
>
> I am experiencing some problems of memory corruption with PetscMemzero().
>
> I set the values of the Jacobian by blocks using MatSetValuesBlocked(). To
> do so, I use some temporary two-dimensional arrays[dof][dof] that I must
> reset at each loop.
>
> Inside FormIJacobian, for instance, I declare the following two-dimensional
> array:
>
>    PetscScalar  diag[dof][dof];
>
> and then, to zero the array diag[][] I do
>
>    ierr = PetscMemzero(diag,dof*dof*sizeof(PetscScalar));

Note that this can also be spelled

  PetscMemzero(diag,sizeof diag);

> Then, inside main(), once dof is determined, I allocate memory for diag as
> follows:
>
>  diag = (PetscScalar**)malloc(sizeof(PetscScalar*) * dof);
>
>  for (k = 0; k < dof; k++){
>   diag[k] = (PetscScalar*)malloc(sizeof(PetscScalar) * dof);
>  }
> That is, the classical way to allocate memory using the pointer notation.

Note that you can do a contiguous allocation by creating a Vec, then use
VecGetArray2D to get 2D indexing of it.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 835 bytes
Desc: not available
URL: <http://lists.mcs.anl.gov/pipermail/petsc-users/attachments/20140514/8a6b3b42/attachment.pgp>


More information about the petsc-users mailing list