#21 Do not use alloca inside a loop
Merged by huzaifas. Opened by ret2libc.
ret2libc/defensive-coding-guide alloca-loops  into  master

no initial comment

The advise is good, but alloca memory can be deallocated on scope exit if the scope contains a VLA. I don't think compilers diagnose this properly.

From the man page it says:

The  alloca() function allocates size bytes of space in the stack frame of the caller.  This temporary space is automatically freed when the function that called alloca() returns to its caller.

If it is deallocated on scope exit it goes against the description, doesn't it?

Huh, it turns out I misremembered, and according to the GCC documentation, calling alloca inhibits VLA deallocation, not the other way round:

The space for a variable-length array is deallocated as soon as the array name’s scope ends, unless you also use alloca in this scope.

https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

A short test program confirms this:

#include <alloca.h>
void f1 (int *, int *);
void f2 (int n)
{
  for (int i = 0; i < n; ++i)
    {
      int a[n];
      int *b = alloca (sizeof (*b) * n);
      f1 (a, b);
    }
}

@fweimer so we are good to commit this right?

@huzaifas It's still not completely accurate.

Maybe add a sentence that discourages mixing VLAs and alloca in the same function?

Ok I will add that!

@ret2libc ok, i will wait for the change in the patch, before i commit :)

1 new commit added

  • Notify about mixing VLA and alloca

@huzaifas @fweimer sentence added about mixing VLA and alloca.

rebased onto 34c100361b0d11ad18d4a2e113d4b97aae770a0d

Pull-Request has been merged by huzaifas

Metadata