Format
#include <stdlib.h> /* also in <malloc.h> and <builtin.h> */ void *_alloca(size_t size);
Language Level: Extension
_alloca is a built-in function that temporarily allocates size
bytes of storage space from the program's stack. The memory space
is automatically freed when the function that called _alloca
returns.
Note: _alloca is faster than other allocation functions, such as malloc, but it has several limitations:
Because _alloca uses automatic storage, programs calling _alloca must not be compiled using the /Gs+ switch. This switch disables stack probes and does not guarantee that enough stack storage will be available. You should use the /Gs- switch, which is the default setting.
Return Value
_alloca returns a pointer to the reserved space. If
_alloca cannot reserve the requested space, the program gets an
out-of-stack exception.
Example
This example uses srand to generate five random numbers.
The numbers determine how much space _alloca is to allocate for
the array barstr. The result is a ragged two-dimensional array of
strings.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h>
int main(void)
{
char *fullbar = "1 2 3 4 5";
int range,rval;
char *barstr[5];
int i;
printf("Bar representation of 5 random numbers ");
printf("(each generated from 1 to 5):\n\n");
/* set seed for rand function using time in seconds */ srand((unsigned int)time(NULL));
for (i = 0; i < 5; i++) {
rval = (rand()+1)%5; /* generate random number from 0 to 4 */
/* for partial copy of fullbar, allocate space on stack for barstr
from 2 to 10 characters long + one space for a null character */
barstr[i] =(char *) _alloca((rval *sizeof(char) << 1)+3);
memset(barstr[i], '\0', (rval *sizeof(char) << 1)+3);
/* copy random sized portion of fullbar */
strncpy(barstr[i], fullbar, ((rval+1)*2));
printf("%s\n", barstr[i]); /* print random length bar */
/***************************************************************************
The output should be similar to the following:
Bar representation of 5 random numbers (each generated from 1 to 5):
1
1 2 3 4
1 2 3
1 2 3 4 5
1 2
***************************************************************************/
}
![]()
calloc -- Reserve and Initialize Storage
free -- Release Storage Blocks
malloc -- Reserve Storage Block
realloc -- Change Reserved Storage Block
Size
<malloc.h>
<stdlib.h>
/Gs compiler option