[MOAB-dev] variable-length arrays

Jed Brown jed at 59A2.org
Tue Nov 17 14:09:22 CST 2009


Jason Kraftcheck wrote:
> Beginning with the C99 standard, the C language has had support for
> automatic-duration variable-length arrays.  For example:
>   void foo( int n ) {
>     int array[n]; // 'n' is *not* a constant
>     ...
>   }
> 
> No C++ standard incorporates this feature yet.  However, given that a) it is
> common for much code to be shared between C and C++ compilers from the same
> vendor, b) this feature has been in the C standard for a decade, and c) this
> feature will be included in the next C++ standard, it seems likely that many
>  C++ compilers support this feature now (e.g The Gnu compiler does.)
> 
> It is possible to get the same functionality in c++ using std::vector
> (except for arrays of bool, and assuming the time to zero the memory isn't
> significant).  However, std::vector allocates storage on the heap while a
> automatic array will (typically) be allocated on the stack.  For a few cases
> involving tight loops where the performance with heap allocation is
> unacceptable, it would be nice to be able to use var-len auto arrays.
> 
> We have not this feature anywhere in MOAB or CGM so far because of possible
> portability issues.  Does anyone have any experience with using
> variable-length automatic arrays in C++ code that is built on diverse systems?

Not from C++, but there are issues even with perfect compiler support,
basically the same as alloca().  Because MOAB doesn't have control over
the environment, it would be irresponsible to put anything large on the
stack.  If you know the array is smaller than some fixed size, you might
as well allocate the array with some constant.  PETSc does something
like the following in a few places

int foo(int n) {
  double array_static[1024],*array = array_static;
  if (n > 1024) array = malloc(n*sizeof double);

  /* ... */

  if (array != array_static) free(array);
  return 0;
}

This is more responsible and essentially the same speed.  A malloc/free
costs 300 to 400 clocks so it only hurts for small sizes.

I do use VLA-pointers extensively.  Compiler support would be the only
reason to avoid them, but I have had no problems (albeit with C99
compilers, not C++).

Jed

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 261 bytes
Desc: OpenPGP digital signature
URL: <http://lists.mcs.anl.gov/pipermail/moab-dev/attachments/20091117/7171135d/attachment.pgp>


More information about the moab-dev mailing list