Append to dynamic array that was allocated via calloc

John Burton via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 25 05:40:13 PDT 2017


I can create a "slice" using non-gc allocated memory.

         int* ptr = cast(int*)calloc(int.sizeof, 10);
         int[] data = ptr[0..10];

If I don't want a memory leak I have to call free(ptr) somewhere 
as it won't be GC collected when data or ptr go out of scope. I 
presume there is nothing wrong with doing the above, other than 
perhaps there being better ways (and the memory leak if not 
free'd)

If I then write this :-

         data ~= 1;

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?




More information about the Digitalmars-d-learn mailing list