_alloca

Description

Allocates memory on the stack.

#include <malloc.h> Required only for function declarations  

void *_alloca( size_t size);

size Bytes to be allocated from stack  

Remarks

The _alloca routine allocates size bytes from the program's stack. The allocated space is automatically freed when the calling function is exited.

Observe the following restrictions when using _alloca:

When you compile with optimization on (either by default or by using one of the /O options), the stack pointer may not be restored properly in functions that have no local variables and that also reference the _alloca function. (This restriction does not apply to DOS32X.) The following program demonstrates the problem:

/* Compile with CL /AM /Ox /Fc */

#include <malloc.h>

void main( void )

{

func( 10 );

}

void func( register int i )

{

_alloca( i );

}

To ensure that the stack pointer is properly restored, make sure that any function referencing _alloca declares at least one local variable.

The pointer value returned by _alloca should never be passed as an argument to free.

The _alloca function should never be used in an expression that is an argument to a function.

Return Value

The _alloca routine returns a void pointer to the allocated space, which is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than char, use a type cast on the return value. The return value is NULL if the space cannot be allocated.

Compatibility

Standards:UNIX

16-Bit:DOS

32-Bit:DOS32X

Use _alloca for compatibility with ANSI naming conventions of non-ANSI functions. Use alloca and link with OLDNAMES.LIB for UNIX compatibility.

See Also

calloc functions, malloc functions, realloc functions

Example

/* ALLOCA.C: This program checks the stack space available before

* and after using the _alloca function to allocate space on the stack.

*/

#include <malloc.h>

#include <stdio.h>

void main( void )

{

char *buffer;

printf( "Bytes available on stack: %u\n", _stackavail() );

/* Allocate memory for string. */

buffer = _alloca( 120 * sizeof( char ) );

printf( "The _alloca function just allocated" );

printf( " memory from the program stack.\n" );

printf( "Enter a string: " );

gets( buffer );

printf( "\"%s\" was stored in the program stack.\n", buffer );

printf( "Bytes available on stack: %u\n", _stackavail() );

}

Output

Bytes available on stack: 1744

The _alloca function just allocated memory from the program stack.

Enter a string: Store this on the stack.

"Store this on the stack." was stored in the program stack.

Bytes available on stack: 1614