www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Purity of alloca()

reply bearophile <bearophileHUGS lycps.com> writes:
Is alloca() pure?
Given the same input alloca() generally returns different pointers, so it's not
a pure function.
But the same is true for the ptr field when you allocate an array on the heap.
And the memory allocated by alloca() never escapes the function, so it looks
more pure than normal heap allocation :-)


import std.c.stdlib: alloca;
pure int foo(int n) {
    auto arr = new int[n];
    for (int i; i < n; i++)
        arr[i] = i;
    return arr[0];
}
pure int bar(int n) { // error: not pure because alloca is not pure
    int* arr = cast(int*)alloca(int.sizeof * n);
    for (int i; i < n; i++)
        arr[i] = i;
    return arr[0];
}
void main() {}


Bye,
bearophile
Jul 02 2010
parent BCS <none anon.com> writes:
Hello bearophile,

 Is alloca() pure?
 
 Given the same input alloca() generally returns different pointers, so
 it's not a pure function.
 
 But the same is true for the ptr field when you allocate an array on
 the heap.
 
 And the memory allocated by alloca() never escapes the function, so it
 looks more pure than normal heap allocation :-)
 
As long as you don't pop the stack and do funky stuff with pointers. Vote++ -- ... <IXOYE><
Jul 02 2010