Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a malloc() needed before a realloc()?

People also ask

When should we 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.

What is the difference between malloc () function and realloc () function?

The malloc() is used to allocate a single block of memory, calloc() is used to allocate multiple blocks of memory, and realloc()is used to reallocate memory that is allocated to malloc() or calloc() functions.

Does realloc use malloc or calloc?

C realloc() method “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory.

Is realloc faster than malloc and free?

If you need to keep your data, use realloc(). It's ~4 times faster than using malloc()/free() and copying your data when scaling up. When scaling down it is 10,000-100,000 times faster.


From Open Groups' specifications:

If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.

If ptr does not match a pointer returned earlier by calloc(), malloc(), or realloc() or if the space has previously been deallocated by a call to free() or realloc(), the behavior is undefined.


malloc is not required, you can use realloc only.

malloc(n) is equivalent to realloc(NULL, n).

However, it is often clearer to use malloc instead of special semantics of realloc. It's not a matter of what works, but not confusing people reading the code.

(Edit: removed mention of realloc acting as free, since it's not standard C. See comments.)