There is precious little information online or on stackoverflow with regards to a function I recently encountered called zmalloc
. (In fact, this is only the 3rd zmalloc
-tagged question on SO).
I gleaned the following:
So my questions are:
Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time. Allocating memory allows objects to exist beyond the scope of the current block.
If you need the dynamically allocated memory to be zero-initialized then use calloc . If you don't need the dynamically allocated memory to be zero-initialized, then use malloc . You don't always need zero-initialized memory; if you don't need the memory zero-initialized, don't pay the cost of initializing it.
Use malloc() if you are going to set everything that you use in the allocated space. Use calloc() if you're going to leave parts of the data uninitialized - and it would be beneficial to have the unset parts zeroed. 3.
The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free.
It looks like zmalloc is part of the redis-tools (https://github.com/antirez/redis-tools). redis is a kind of database which keeps stuff in memory (http://redis.io/).
Typically malloc replacements are developed because some target systems do not provide a suitable malloc, or because the caller needs extra functionality. I think zmalloc is a pretty simple wrapper of the system malloc/free, just keeping track of the overall memory allocated. No automatic free involved. The post you pointed to also explains the need: The database can be configured to not use more than some amount of memory and thus needs to keep track of the overall consumption.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With