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

@@ -676,6 +676,14 @@ 

  function, check if `malloc` had been called,

  and free the buffer as needed.

  

+ Remember that memory allocated on the stack through `alloca`

+ is released at the end of the function and not at the end of

+ the block where it is defined, thus it is reccommended to not

+ call `alloca` inside a loop. In this regard, VLA behaves better,

+ considering the memory allocated with VLA is released at the end

+ of the block that defines them. Do not mix VLA and `alloca` though,

+ otherwise this behaviour is not guaranteed for VLA either!

+ 

  [[sect-Defensive_Coding-C-Allocators-Arrays]]

  === Array Allocation

  

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?

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

1 new commit added

  • Notify about mixing VLA and alloca
2 years ago

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

rebased onto 34c1003

2 years ago

Pull-Request has been merged by huzaifas

2 years ago
Metadata