![]() |
![]() |
![]() |
Allocate automatic space from the stack
#include <alloca.h> void* alloca( size_t size );
libc
The alloca() function allocates space for an object of size bytes from the stack. The allocated space is automatically discarded when the current function exits.
This function shouldn't be used in an expression that's an argument to a function.
A pointer to the start of the allocated memory, or NULL if there's insufficient stack space available.
#include <stdio.h> #include <string.h> #include <malloc.h> #include <stdlib.h> FILE *open_err_file( char *name ) { char *buffer; /* allocate temporary buffer for file name */ buffer = (char *)alloca( strlen( name ) + 5 ); if( buffer ) { FILE *fp; sprintf( buffer, "%s.err", name ); fp = fopen( buffer, "w" ); return fp; } return (FILE *)NULL; } int main( void ) { FILE *fp; fp = open_err_file( "alloca_test" ); if( fp == NULL ) { printf( "Unable to open error file\n" ); } else { fprintf( fp, "Hello from the alloca test.\n" ); fclose( fp ); } return EXIT_SUCCESS; }
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | Yes |
Signal handler | Yes |
Thread | Yes |
Don't use alloca() as an argument to a function.
![]() |
![]() |
![]() |