Dynamic array ot not

Ali Çehreli acehreli at yahoo.com
Sun Jan 16 16:21:29 UTC 2022


On 1/16/22 07:32, Salih Dincer wrote:
 > On Sunday, 16 January 2022 at 11:43:40 UTC, Ali Çehreli wrote:
 >>
 >> void main() {
 >>   enum count = 7;
 >>
 >>   // Allocate some memory
 >>   void* rawData = malloc(int.sizeof * count);

In practice, malloc'ed memory is cleared e.g. by memset(). Or, there is 
calloc() which returns memory filled with zeros. It takes two parameters:

   void* rawData = calloc(count, int.sizeof);

(Of course, one also needs to check that the returned value is not null 
before using it.)

 > If count is not equal to 8 I get weird results! The reason of course, is
 > the free():
 > // [93947717336544, 1, 2, 3, 4, 5, 6]

I didn't know free wrote into the freed buffer but since it's undefined 
behavior, we shouldn't even be able to know whether it did or not. :/

 > [Here](https://run.dlang.io/is/yFmXwO) is my test code.

You have the following loop there:

   foreach(i, ref s; slice) s = cast(int)i;

Note that the assignment operator into a malloc'ed buffer works only for 
some types like the fundamental ones. Otherwise, the opAssign() of a 
user-defined type may be very unhappy with random or zero data of 'this' 
object. (Note that there really wouldn't be any user-defined type in the 
buffer; we would have just cast'ed it to fool ourselves.) The reason is, 
opAssign() may have to destroy existing members of 'this' during the 
assignment and destroying random or zero data may not work for a 
particular type.

So, one would have to emplace() an object in that memory. Here is my 
explanation:

   http://ddili.org/ders/d.en/memory.html#ix_memory.construction,%20emplace

Ok, this is too much theory and those are parts of the reasons why we 
don't generally use calloc or malloc. :)

Ali



More information about the Digitalmars-d-learn mailing list