alloca

From RAD Studio
Jump to: navigation, search

Go Up to malloc.h Index


Header File

malloc.h

Prototype

void *alloca(size_t size);

Description

Allocates temporary stack space.

alloca allocates size bytes on the stack; the allocated space is automatically freed up when the calling function exits.

The use of alloca is not encouraged. In the try-block of a C++ program the alloca function should never be used. If an exception is thrown, any values placed on the stack by alloca will be corrupted.

Return Value

If enough stack space is available, alloca returns a pointer to the allocated stack area. Otherwise, it returns NULL.

Portability

POSIX ANSI C ANSI C++ Win32 Win64 OS X
alloca +

Example

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

void test(int a) {
    char *newstack;
    int len = a;
    char dummy[1];
    dummy[0] = 0; /* force good stack frame */
    printf("SP before calling alloca(0x%X) = 0x%X\n", len, _SP);
    newstack = (char *) alloca(len);
    printf("SP after calling alloca = 0x%X\n", _SP);
    if (newstack)
        printf("Alloca(0x%X) returned %p\n", len, newstack);
    else
        printf("Alloca(0x%X) failed\n", len);
}

void main() {
    test(256);
    test(16384);
}