Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would one use malloc over zmalloc?

Tags:

c

malloc

zmalloc

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:

  • zmalloc automatically keeps track of, and frees unfreed memory, similar to C++ smart pointers.
  • zmalloc apparently enables some metrics, at least in the case of the redis source.

So my questions are:

  1. What flexibility does one lose, then, in using zmalloc over malloc? i.e. what benefits do malloc continue to offer that zmalloc does not?
  2. Is zmalloc non-standard in C11? Is this a custom-built function?
like image 969
Engineer Avatar asked Mar 29 '14 10:03

Engineer


People also ask

When would you use malloc?

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.

Why should we prefer malloc over Calloc?

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.

When would you use calloc over malloc?

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.

When should I use free and malloc?

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.


1 Answers

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.

like image 192
Peter - Reinstate Monica Avatar answered Oct 10 '22 01:10

Peter - Reinstate Monica