What does alloca(0) do and return on various platforms?

1.9k Views Asked by At

Does alloca() returns NULL if the size given is 0?

A quick search reveals that alloca(0) force garbage collection in some cases! but I am mostly interested by return value.

thanks

4

There are 4 best solutions below

0
On BEST ANSWER

According to Linux man pages

Conforming to

This function is not in POSIX.1-2001.

Notes

The alloca() function is machine- and compiler-dependent.

So alloca()ing 0 size elements is not legal but not defined

I don't have a specifical example of the return value when size=0. Please, take a look at this question and "Notes on the GNU Version" at the first link

2
On

According to this manpage, alloca will allocate memory on the stack, and it will either succeed, or make your program crash.

Now, for an allocation of 0 bytes, you should not bother about the returned value: since there are 0 byte, there is no space for you to write, and no matter if the pointer value returned is 0x1234 or NULL, the program should crash anyway.

0
On

On Windows, _alloca(0); returns the stack pointer (with some fixed offset.) This may be necessary in some exceptional situations when C code needs to know the RSP CPU register from within an x64 process (since inline assembly is not supported for 64-bit builds in Visual Studio.)

Keep in mind though, that calling _alloca(0); will allocate some memory on the stack, so make sure not to call it repeatedly in the same local scope, as otherwise that may deplete your stack and cause the stack overflow exception.

As a much better alternative, consider calling _AddressOfReturnAddress() intrinsic instead.

0
On

The gcc-2.95 implementation of alloca allocates memory from the heap using malloc itself. In the context of that implementation alloca (0) is equivalent to: free (/*all the memory that was allocated with alloca when the stack pointer was deaper*/). Here's a quotation from a commentary in the alloca.c file of the gcc-2.95.

The general concept of this implementation is to keep track of all alloca-allocated blocks, and reclaim any that are found to be deeper in the stack than the current invocation. This heuristic does not reclaim storage as soon as it becomes invalid, but it will do so eventually.

As a special case, alloca(0) reclaims storage without allocating any. It is a good idea to use alloca(0) in your main control loop, etc. to force garbage collection.

By the way in this implementation alloca(0) returns NULL.