cleaning up two very nasty coding habits

Barry Smith bsmith at mcs.anl.gov
Tue Nov 17 21:21:00 CST 2009


   When starting to code PETSc 2.0 I introduced two nasty habits

1) since we called malloc() directly and some mallocs don't like  
allocating zero length I would often allocate 1 additional space to  
make sure I did not request a zero size. Giving things like  
PetscMalloc((n+1)*sizeof(something),&something); This leads to  
confusing code because we don't know when the 1 belongs or not.

2) in order to reduce the number of mallocs I would do a single malloc  
for several variables. For example, PetscMalloc((n+m 
+1)*sizeof(PetscScalar),&buf1); buf2 = buf1 + n;

   Later I changed PetscMalloc()/Free() to allow 0 length mallocs. I  
also introduced PetscMalloc2-3-4-5() to efficiently and cleanly share  
one malloc. Thus 1 and 2 became unnecessary. Since they are downright  
disgusting I am trying to eliminate 2) and would like also to reduce 1)

   This fixes will likely introduce some hard to determine bugs in the  
near future (or already have). Please avoid habits 1 and 2 from now on  
in the PETSc code base.

    Thanks

     Barry




More information about the petsc-dev mailing list