Append to dynamic array that was allocated via calloc

John Burton via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 25 06:29:29 PDT 2017


On Tuesday, 25 July 2017 at 13:24:36 UTC, Mike Parker wrote:
> On Tuesday, 25 July 2017 at 12:40:13 UTC, John Burton wrote:
>> [...]
>
> This should give you the answer:
>
> writefln("Before: ptr = %s capacity = %s", slice.ptr, 
> slice.capacity);
> slice ~= 1;
> writefln("After: ptr = %s capacity = %s", slice.ptr, 
> slice.capacity);
>
> It shows that before the append, the capacity is 0. That 
> indicates that any append will cause a new allocation -- from 
> the GC. The next writefln verifies this by showing a different 
> value for ptr and a new capacity of 15.
>
> In order for this to work, you'll need to manually manage the 
> length and track the capacity yourself. If all you want is to 
> allocate space for 10 ints, but not 10 actual ints, then 
> something like this:
>
> size_t capacity = 10;
> int* ints = cast(int*)malloc(int.sizeof * capacity);
> int[] slice = ints[0 .. 10];
> slice.length = 0;
> slice ~= 1;
> --capacity;
>
> Then reallocate the array when capacity reaches 0. Or just use 
> std.container.array.Array which does all this for you.

Ok so it sounds like this is "safe" in that it will copy my data 
into GC memory and all work safely. I'll need to somehow keep 
track of my original memory and free it to avoid a memory leak...
(I don't plan to do any of this, but I wanted to understand)(


More information about the Digitalmars-d-learn mailing list