www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 4418] New: Is alloca() pure?

reply d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=4418

           Summary: Is alloca() pure?
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc



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 of an array newly allocated on the heap
inside a pure function, 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) { // line 9, error
    int* arr = cast(int*)alloca(int.sizeof * n);
    for (int i; i < n; i++)
        arr[i] = i;
    return arr[0];
}
void main() {}


Compiling that program with dmd v2.047 produces:
test.d(9): Error: pure function 'bar' cannot call impure function 'alloca'

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Jul 02 2010
next sibling parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=4418


bearophile_hugs eml.cc changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
         Resolution|                            |INVALID



alloca() can't be pure because you can use alloca() inside a loop too (see bug
3822 ), and an expected optimization of pure functions is to pull them out of
loops (because they always return the same result or throw an exception/error,
see bug 4453 ). I prefer alloca() to free its memory only at the end of the
function (and not at the end of the scope of the for loop).

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Jul 13 2010
prev sibling parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=4418




A D function that uses some kind of implementation of C99 Variable Length
Arrays can be pure (and they get deallocated at the end of their scope, for
example at the end of a for loop, and not only at the end of the function).

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Jul 13 2010