Introduction to malloc() in C++
Malloc function in C++ is used to allocate a specified size of the block of memory dynamically uninitialized. It allocates the memory to the variable on the heap and returns the void pointer pointing to the beginning address of the memory block. The values in the memory block allocated remain uninitialized and indeterminate. In case the size specified in the function is zero then pointer returned must not be dereferenced as it can be a null pointer, and in this case, behavior depends on particular library implementation. When a memory block is allocated dynamically memory is allocated on the heap but the pointer is allocated to the stack.
Malloc function is present in <cstdlib> header file in library of C++. This is used to invoke dynamic memory allocation to the variables where the size of the block is defined at the compile time. Below is the syntax for malloc function:
void* malloc(size_t size);
Only one parameter needs to be passed to call the malloc method that is the size of the memory block one needs to allocate. The data type for this parameter is size_t. Memory allocated is initialized with random values and must be initialized again.
Return Type: void* is a return type. This signifies that this method returns a pointer to the address of the first memory block allocated on the heap. This pointer is made on the stack. In case the size specified in the parameters is 0 then the pointer being returned is null and shall not be referenced.
How does the malloc() method work in C++?
Malloc function is present in <cstdlib> header file of C++ library. This method is used to allocate memory block to a variable or array on heap where variables have a better life.
When this method is called for a specified size_t variable, the compiler searches the same memory block size on the heap and returns a pointer to the starting address of that memory block. The pointer returned is a void pointer that means it can be easily converted to a pointer of any datatype. In case the specified size for a memory block is 0 then a NULL pointer is returned working in indeterminate behavior, and shall not be dereferenced.
This function does not call the constructor. Since memory is allocated dynamically thus leads to avoid various segmentation fault errors. Memory allocated using this function cannot be overridden that is no other program will be able to use that memory block until it is freed from that particular pointer. Thus one must free the memory being allocated using the malloc method and thus we can experience good memory management by our system and enhanced performance.
Also, we must note that the size of the block being specified needs to be calculated manually as per the requirement such as in case the array consists of int type values thus memory being allocated must be multiple of memory size of an int variable.
Examples to Implement malloc() in C++
Below are examples mentioned:
In our first example we will use malloc function to create an array for 6 number of elements of int type:
using namespace std;
my_ptr = (int*) malloc(6*sizeof(int));
cout << "Lets intilize 6 memory blocks with odd numbers" << endl << endl;
for (int i=0; i<6; i++)
my_ptr[i] = (i*2)+1;
cout << "Lets see the values" << endl << endl;
for (int i=0; i<6; i++)
cout << "Value at position "<<i << " is "<< *(my_ptr+i) << endl;
Let’s see the scenario if 0 is specified as size in malloc function:
If the size is 0, then malloc() returns either NULL or a unique pointer value that can later be successfully passed to free(). That means, there is no guarantee that the result of a malloc(0) is either unique or not NULL.
using namespace std;
size_t size =0;
int *my_ptr = (int *)malloc(size);
cout << "Null pointer has been returned";
cout << "Memory has been allocated at address" << my_ptr << endl;
Advantages of malloc() in C++
There are a lot of advantages to using the malloc method in one’s application:
Dynamic Memory allocation: Usually we create arrays at compile time in C++, the size of such arrays is fixed. In the case at run time we do not use all the space or extra space is required for more elements to be inserted in the array, then this leads to improper memory management or segmentation fault error.
Heap memory: Local arrays that are defined at compile time are allocated on the stack, which has lagged in memory management in case the number of data increases. Thus one needs to allocate memory out of the stack, thus malloc comes into the picture as it 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.
Variable-length array: This function helps to allocate memory for an array whose size can be defined at the runtime. Thus one can create the number of blocks as much as required at run time.
Better lifetime: Variable created using malloc method is proved to have a better life than the local arrays as a lifetime of local arrays depends on the scope they are being defined and cannot access out of their scope. But variables or arrays created using malloc exist till they are freed. This is of great importance for various data structures such as linked list, binary heap, etc.
Malloc method is used to allocate memory to the variables dynamically in the form of an array and returns a void pointer pointing to the starting address of the memory block. The null pointer is returned in case the size of the block specified is 0. This memory is allocated on the heap and the pointer is made on the stack. Memory allocated cannot be overridden and the size must be calculated manually.
This is a guide to malloc() in C++. Here we discuss an introduction to malloc() in C++, syntax, how does it work, examples. You can also go through our other related articles to learn more –