Variable length arrays under -betterC?

Steven Schveighoffer schveiguy at gmail.com
Tue Apr 18 19:56:53 UTC 2023


On 4/17/23 11:34 AM, DLearner wrote:
> Requirement is to write some D code (which avoids the GC), that will be 
> called from C.
> So simple approach seemed to be to write D code under -betterC 
> restrictions.
> 
> However, also need variable length arrays - but D Dynamic Arrays not 
> allowed under -betterC.

> Any ideas how to implement variable length arrays under -betterC?

variable-length arrays (i.e. slices) are valid in betterC. What isn't 
allowed is *GC-allocating* them and *appending* to them in betterC.

```d
int[] arr; // fine
// arr ~= 5; // nope, uses GC
arr = (cast(int *)malloc(int.sizeof * 5))[0 .. 5]; // fine
arr = arr[0 .. 3]; // also fine, no allocations needed
arr = (cast(int*)realloc(arr.ptr, int.sizeof * 10))[0 .. 10]; // fine, 
but leaks the original pointer
free(arr.ptr); // fine
```
What you *likely* want is an array type that handles some of the 
lifetime issues, or at least some UFCS/factory functions to make life 
easier (the above code is as bad as C code (except for the slicing)). 
But variable-length arrays work just fine as-is.

As with any manual memory management system, you need to handle the 
lifetime more carefully and explicitly. There's a reason why reference 
counting is hard to implement.

-Steve


More information about the Digitalmars-d-learn mailing list