The function malloc() in C++ is used to allocate the requested size of bytes and it returns a pointer to the first byte of allocated memory. A malloc() in C++ is a function that allocates memory at the runtime, hence, malloc() is a dynamic memory allocation technique. It returns a null pointer if fails.
pointer_name = (cast-type*) malloc(size);
Here, size is an unsigned integral value (cast to size_t) which represents the memory block in bytes
malloc() in C++ allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. Malloc function is present in <cstdlib> header file.
Return Types of malloc()
If the size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced.
- void pointer is used to the uninitialized the initialized memory block that is allocated by the function
- null pointer if the allocation fails
Working and Allocation of Memory Blocks Using malloc()
Memory has been allocated at address 0x8cae70
free() function in C++ is used to dynamically de-allocate the memory.
Where Should Malloc be used?
1. Dynamic Memory allocation
Dynamic Memory Allocation helps us allocate a piece of memory as per the user’s demand. It returns a pointer to the start of that memory, which could be treated similarly to an array.
2. Heap memory
malloc() allocates the memory location on the heap and returns a pointer on the stack pointing to the starting address of the array type memory being allocated whereas the static array size put a hard upper limit on how much data the program could process at any one time, without being recompiled.
3. Better lifetime
Difference between new and malloc()
|new is an operator||malloc() is a function|
|new calls constructors||malloc() does not call constructors|
|new returns the exact data type||malloc() returns void*|
|new never returns a NULL (will throw on failure)||malloc() returns NULL|
|Reallocation of memory not handled by new||Reallocation of memory can be handled by malloc|
|new allocates memory and calls the constructor||malloc only allocates the memory|