3 Ekim 2021 Pazar

alloca metodu - standart C metodu değildir Kullanmayın

Giriş
Şu satırı dahil ederiz
#include <alloca.h>
Bu metod standart C veya POSIX metodu değildir. Gnu C kütüphanesinde bulunur. Windows'ta ise _alloca() şeklinde kullanılabilir.

Bu metod stack üzerinde yer ayırır. Açıklaması şöyle
The alloca() function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller.
alloca vs Variable Length Array (VLA)
alloca metodu VLA'dan da eskidir. Açıklaması şöyle. BSD 3 1970'lerin sonuna doğru vardı.
CONFORMING TO

This function is not in POSIX.1-2001.

There is evidence that the alloca() function appeared in 32V, PWB, PWB.2, 3BSD, and 4BSD. There is a man page for it in 4.3BSD. Linux uses the GNU version.
Aslında bu metoda C dilinde gerek yoktur! Çünkü C dili variable length array (VLA) kullanarak stack üzerinde boyutu runtime'da belirlenen yer ayırabilmeye imkan verir.

Ancak C++ variable length array kullanımına izin vermediği için bazen faydalı olabiliyor.
Örnek
alloca yerine VLA kullanılabileceğini görmek için şöyle yaparız
#include <stdio.h>
#include <alloca.h>

void foo(int n)
{
    int a[n];
    int *b=alloca(n*sizeof(int));
    int c[n];
    printf("&a=%p, b=%p, &c=%p\n", (void *)a, (void *)b, (void *)c);
}

int main()
{
    foo(5);
    return 0;
}
Örnek
Örnekte placement new için yer alloca ile stack üzerinde oluşturuluyor.