Append to dynamic array that was allocated via calloc

Dukc via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 25 06:13:53 PDT 2017


On Tuesday, 25 July 2017 at 12:40:13 UTC, John Burton wrote:
> What happens? It seems to successfully append an extra value to 
> the array. It appears to "work" when I try it in my compiler 
> but I don't understand how. Will this be trying to write beyond 
> the memory I calloc'ed?

The language makes no guarantee. It may append in-place if the 
operating system finds out that the memory after it is not in 
use. But it may also allocate a whole new array (with gc) and 
copy the whole thing there. And since the original array was 
allocated manually, that results in a memory leak. Unless you 
check for that by storing the appended array in a new variable 
and compare their pointers.

The why part here is for efficiency reasons. We do not want to 
copy every time one appends, but if there's something in way that 
just needs to be done.

I think the correct way here is to use realloc(). Or 
std.container.Array. It is well possible there are other good 
options too.


More information about the Digitalmars-d-learn mailing list