is the array literal in a loop stack or heap allocated?

ryuukk_ ryuukk.dev at gmail.com
Wed Oct 11 03:31:32 UTC 2023


On Wednesday, 11 October 2023 at 02:54:53 UTC, mw wrote:
> Hi,
>
> I want to confirm: in the following loop, is the array literal 
> `a` vs. `b` stack or heap allocated? and how many times?
>
> void main() {
>
> int[2] a;
> int[] b;
>
> int i;
> While(++i <=100) {
>
>   a = [i, i+1];  // array literal
>   b = [i, i+1];
>
> }
>
> }
>
>
> Thanks.


a is a static array, therefore it won't allocate any, it's a 
memcpy

b will be heap allocated, and it'll do an allocate at each 
iteration


```D
void test_b()
{
     int[] a;
     int i;
     while (++i <= 100)
     {
         a = [i, i + 1];
         printf("%p\n", a.ptr);
     }
}
```

You can run this, and it'll print a different address each time


If you add `[]` it'll do range based copy (memcpy), but since the 
array is not initialized, it has a length of 0, so you only need 
to allocate once (either with GC or with malloc)

```D
void test_b()
{
     int[] a;
     int i;

     a.length = 2; // initialize the heap allocated array here

     // or with malloc:
     // auto ptr = malloc(int.sizeof * 2);
     // a = cast(int[]) ptr[0 .. int.sizeof * 2];

     while (++i <= 100)
     {
         a[] = [i, i + 1];
         printf("%p\n", a.ptr);
     }
}
```

Otherwise you'd get: ``core.exception.RangeError at onlineapp.d(18): 
Range violation``

I don't use D with the GC, so my memory about it is probably 
foggy, but i'm pretty sure what i said is right, please anyone 
correct me if i'm wrong



More information about the Digitalmars-d-learn mailing list