On 09/28/2014 08:58 PM, Lag Programming wrote:
@Nikolay
Thank you for your answer. :) Now that you've answered, can you further respond to the following question: why is it needed to zero fill the memory allocated that exceeds the requested value? a) "pointer:=allocmem(initialsize); reallocmem(pointer,increasedsize);". I don't see the benefits of the zero filled bytes that exceed the "initialsize" value at "pointer". Once you "reallocmem" to increase size you don't expect to have the additional space filled with zeros. This means that an attempt to somehow optimize code because of initial more than enough zero filling is something hard to believe in.
To be honest, I don't know. It's probably for some extra safety, e.g. to minimize the damage from the undefined behaviour of reading beyond the memory block you allocated or to be able to detect heap corruption if you overwrite these zeros.
b) if your affirmation is right then for "bytepointer:=allocmem(sizeof(byte));" we would zero fill at least 3 or 7 times the necessary amount. At the moment I don't see nothing good at that. The closest thing that got into my mind was the arrays. For an unknown reason to me, yet(somebody please enlighten me) dynamic arrays are always zero filled. But even these arrays don't use allocmem. It was something that got me curious. Instead of allocmem, getmem&fillchar are used separately :) (see dynarr.inc fpc_dynarray_setlength). Somebody saw the bottleneck(waste, whatever you want to call it) with this allocmem situation. So. Can you please further develop you answer according to this message.

I seriously doubt it makes any difference on 32-bit and 64-bit architectures. AFAIK, on a modern CPU, it takes exactly the same amount of time to write 32-bits to a 32-bit aligned address as to write a single byte. But the extra call to MemSize probably does add some extra overhead, yes. As for why are dynarrays zero filled, I can only guess, but these things come to mind:

1) delphi compatibility
2) zero filling ensures that magic reference counted types like ansistrings, interfaces and other dynarrays are properly initialized. The same reason class instances are initialized with zeros before the constructor is called.

Nikolay
_______________________________________________
fpc-devel maillist  -  fpc-devel@lists.freepascal.org
http://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel

Reply via email to