On Sun, Jan 16, 2022 at 08:21:29AM -0800, Ali Çehreli via Digitalmars-d-learn wrote: > 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.
Correction: malloc() is not guaranteed to clear the allocated memory. Possibly for "performance reasons". Usually, though, I'd recommend using calloc() instead to initialize the allocated memory and prevent surprising results. (E.g., you allocate a buffer expecting it would be zeroed, but it isn't so the code that assumes it does produces garbled results. Or worse, if you're allocating memory for, e.g., a packet buffer to be transmitted across the network, failing to initialize it may leak the past contents of that memory to the internet. Cf. HeartBleed.) [...] > > 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. :/ [...] This is likely caused by the implementation of malloc/free. Some implementations store pointers and other tracking information inside the free blocks themselves instead of using a separate data structure to track free memory (e.g., the start of the block may contain a pointer to the next available block). After calling free(), that memory is now a free block, so the implementation may start storing such information within the block. Some memory allocator implementations may also store a canary value at the beginning of freed blocks to detect double free's (i.e., a value unlikely to occur in user data that, if detected by free(), may indicate a bug in the code that's trying to free the same block twice). T -- Debian GNU/Linux: Cray on your desktop.