I wonder what is the difference between both functions.

In C++, the difference between new and malloc is easier: new allocates memory by calling the constructor.

What about PETSc ? In the example, it seems to be pretty close:

in dm/examples/tutorials/ex6.c:

struct _p_FA {
  MPI_Comm   comm[3];
  PetscInt   xl[3],yl[3],ml[3],nl[3];    /* corners and sizes of local vector in DMDA */
  PetscInt   xg[3],yg[3],mg[3],ng[3];    /* corners and sizes of global vector in DMDA */
  PetscInt   offl[3],offg[3];            /* offset in local and global vector of region 1, 2 and 3 portions */
  Vec        g,l;
  VecScatter vscat;
  PetscInt   p1,p2,r1,r2,r1g,r2g,sw;
typedef struct _p_FA *FA;
FA         fa;

In ksp/ksp/examples/tutorials/ex42.c:

PetscMalloc(sizeof(struct _p_CellProperties),&cells);

The rule is just: using PetscMalloc for a structure, and PetscNew for a pointer of structure?

  • $\begingroup$ See documentation, which says what they do: mcs.anl.gov/petsc/petsc-current/docs/manualpages/Sys/… mcs.anl.gov/petsc/petsc-current/docs/manualpages/Sys/… $\endgroup$ – Kirill Mar 25 '16 at 14:22
  • $\begingroup$ Thanks but I ask the question because it is not explicit enough for me. If the difference is just that it zeros the memory, then PetscCalloc does the same no? $\endgroup$ – guhur Mar 25 '16 at 14:36
  • 1
    $\begingroup$ I think the main difference is that New says "memory allocated, sized to match pointer type", whereas Malloc accepts "number of bytes to allocate", so New figures out the number of bytes to allocate from the pointer type. Also, nitpick: your description of what new does in C++ isn't quite correct, it allocates memory, then calls the constructor: en.cppreference.com/w/cpp/language/new $\endgroup$ – Kirill Mar 25 '16 at 14:53
  • 2
    $\begingroup$ In fact, New is defined to be Calloc1: bitbucket.org/petsc/petsc/src/… $\endgroup$ – Kirill Mar 25 '16 at 14:57
  • 1
    $\begingroup$ Yes, the name predates the auto-sized allocators (Malloc1, Calloc1, etc.) and should probably be removed in favor of just calling Calloc1 directly. Note that it is more frequently called via PetscNewLog which helps to discover the origin of memory leaks. $\endgroup$ – Jed Brown Mar 25 '16 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.