Bug 4418 – Is alloca() pure?

Status
RESOLVED
Resolution
INVALID
Severity
enhancement
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-07-02T09:38:00Z
Last change time
2010-07-13T09:47:55Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2010-07-02T09:38:04Z
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'
Comment #1 by bearophile_hugs — 2010-07-13T09:44:55Z
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).
Comment #2 by bearophile_hugs — 2010-07-13T09:47:55Z
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).