[MOAB-dev] [PATCH 1/2] iMesh_MOAB: do not allocate new memory for count=0 items

Jed Brown jed at 59A2.org
Fri Jun 10 07:23:02 CDT 2011


Upon re-reading the iMesh.h spec, this would be a change of

If a list argument is unallocated (the list pointer points to a NULL value)
or if the incoming value of the allocated size is zero, the list storage
will be allocated by the implementation.  IN ALL CASES, MEMORY ALLOCATED BY
ITAPS INTERFACE IMPLEMENTATIONS IS DONE USING THE C MALLOC FUNCTION, AND CAN
BE DE-ALLOCATED USING THE C FREE FUNCTION.

to only allocating memory if the result size is also positive. I think my
semantics are much more practical. The only place where it is backward
incompatible is when the caller passes in

list = undefined;
alloc = 0;
iMesh_callReturningList(...,&list,&alloc,&size,...);
for (i=0; i<size; i++) use(list[i]);
free(list);

This can be fixed by simply setting list = NULL before the call. Doing so is
no burden and if anything, makes the code clearer. In the interest of
clarity, I don't think it would be unreasonable to require that BOTH
list=NULL and alloc=0 for library-allocated memory. It becomes an
iBase_BAD_ARRAY_SIZE if list=non-NULL, alloc=0, and a positive number of
items are to be returned.

In any reasonable scenario I can envision, the caller knows statically
whether they want the library to allocate memory or not. The caller would
need a run-time check to determine whether they computed an expected array
length that was positive or equal to zero.

For my use case (filling a preallocated contiguous buffer in segments) the
user would need to have an if statement and avoid the call when an empty
array is expected. This makes user code ugly and fragile.

On Fri, Jun 10, 2011 at 14:08, Jed Brown <jed at 59a2.org> wrote:

>
> It is relatively common to fill a buffer with consecutive queries, some
> of which may return zero items.  In such scenarios, the user passes in a
> valid pointer, but occasionally a length of 0.  In such scenarios,
> having the library allocate a new buffer of zero length is not
> desirable.
>
> On the other hand, if a user knowingly passes in a length of zero, but
> undefined pointer value, they would expect the library to return a
> pointer that can safely be passed to free().  A workaround is to nullify
> the pointer prior to calling iMesh with expectation of a new array.
> ---
>  itaps/imesh/iMesh_MOAB.hpp |    2 +-
>  1 files changed, 1 insertions(+), 1 deletions(-)
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mcs.anl.gov/pipermail/moab-dev/attachments/20110610/0b5185a0/attachment.htm>


More information about the moab-dev mailing list