# PETSc - difference between PetscNew and PetscMalloc

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;
PetscNew(&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?

• 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/… – Kirill Mar 25 '16 at 14:22
• 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? – guhur Mar 25 '16 at 14:36
• 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 – Kirill Mar 25 '16 at 14:53
• In fact, New is defined to be Calloc1: bitbucket.org/petsc/petsc/src/… – Kirill Mar 25 '16 at 14:57
• 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. – Jed Brown Mar 25 '16 at 15:20