[petsc-dev] PetscMalloc for size zero

Barry Smith bsmith at mcs.anl.gov
Thu Jan 30 14:32:09 CST 2014


On Jan 30, 2014, at 2:15 PM, Jed Brown <jed at jedbrown.org> wrote:

> Barry Smith <bsmith at mcs.anl.gov> writes:
>>>   Here is what I suggestion. Someone suggest (i.e.. write) a refactorization of PetscMalloc(), PetscMallocn() that handles correctly any of the sizes being zero correctly in a branch and see how it goes.
>>> 
>>> I have pushed it. It looks simple to me
>> 
>>   I don’t see how this can possibly work
>> 
>> #if defined(PETSC_USE_DEBUG)
>> #define PetscFree2(m1,m2)   (PetscFree(m2) || PetscFree(m1))
>> #else
>> #define PetscFree2(m1,m2)   ((m2)=0, PetscFree(m1))
>> #endif
>> 
>>  You need to free the first m[i] that is not null. If m1 was null in the optimized form you never free anything.
>> 
>>   These macros are getting horrible, can they become something cleaner?
> 
> Why do we want this behavior?  

   Matt feels that having zero space allocated items always as NULL is useful. Perhaps as a debugging/error determining issue since no one can “accidentally” use the location returned by malloc(0) and in the debugger one won’t mistakenly think that a pointer which contains something returned by malloc(0) has a legitimate value in it.


> Can we see some concrete code that is
> affected by this behavior?  We needed PetscMalloc[2-7] to work in
> optimized mode, so nothing in PETSc should be depending on it.

   What does “it” here refer to?  And what do you mean by “depending on”.  Certainly we could make PetscMallocn() and PetscFreen() behave in a way Matt suggests even in optimized code (if we choose to).


   Some notes: 

   We currently mark freed pointers with a NULL so they cannot be accidentally used at a later time. 

   In Jed’s model something a “zero length space” will have the value NULL and something not. There is, AFAIK, no tool to check the address and see if it is a real pointer or a pointer to an invalid location.

   With Matt’s scheme we could also mark “zero length space” with a NULL. In an ideal world I could see having a different specific value for “zero length space” such as INVALIDPOINTER then one could distinguish the two values and their different meanings.  Alias I don’t control the ideal C world. 

   I agree with Jed that we don’t want any PETSc code to be dependent on PetscMallocn(0) always being NULL in all cases; but I understand Matt’s argument that having PetscMallocn() always being NULL makes debugging easier.

   Barry




 





More information about the petsc-dev mailing list