malloc() and calloc() in C++
Definition of malloc()?
A malloc (memory allocation function) is a function in which memory is allocated at runtime. This function can be used with any pointer type as it returns the empty pointer. This null pointer can be converted into a pointer that points to a memory of a specific type.
Characteristics of the malloc() function.
- It dynamically assigns a large block of memory of a given size.
- This function does not make the value zero and returns only the starting address.
- In the malloc() function, there is only 1 argument.
- The malloc() function uses the sizeof() operator to get the required memory for allocation.
Syntax of malloc()
var_name= (data_type*) malloc (sizeof(data_type));
where,
- var_name = name of the variable where the pointer is to be stored
- data_type = the data type in which we want typecasting to get the pointer of the specified type.
- sizeof() = it is used to get the required memory for allocation.
This function can be initialized using the <cstdlib> library in C++.
We can use the realloc() function to change the memory size if there is insufficient memory. Since all dynamic memory requests are satisfied using the heap memory, malloc() also allocates memory on the heap and returns a pointer to it. The heap has very little memory. So when our code starts execution, it marks the used memory, and when our code finishes its work, it frees the memory using the free() function. If it is out of memory and our code tries to access memory, malloc() will return a NULL pointer. With the free() function, the memory that malloc() has allocated can be released.
Types of Return Values for the malloc() Function.
The return value depends on implementing the public library (it may or may not be a null pointer) if the size is zero, but the returned pointer must not be discarded.
- The void pointer de-initializes an initialized memory block the function allocates.
- The null pointer is used when the allocation fails.
Program to illustrate the use of malloc() function in C++
1. Allocating memory using malloc()
CODE
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int size;
int* ptr = (int*)malloc(sizeof(size)); // malloc initialization
if (ptr == NULL) { // if no pointer is initialised
cout << "Null pointer has been returned";
}
else {
cout << "Memory has been allocated at address "<< ptr << endl; // if the memory is initialised
}
free(ptr);
return 0;
}
OUTPUT
![malloc() and calloc() in C++](https://static.tutorialandexample.com/cpp/malloc-and-calloc-in-cpp1.png)
2. Initializing malloc() and storing values
CODE
#include <iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int len =5;
int *ptr;
ptr = (int*) malloc(sizeof(int)*len); // allocating memory to the pointer variable using malloc()
for(int i=0;i<len;i++)
{
cout << "Enter a number : " << endl;
cin >> *(ptr+i);
}
cout << "\nYou have entered : " << endl;
for(int i=0;i<len;i++)
{
cout << *(ptr+i) << endl;
}
free(ptr);
return 0;
}
OUTPUT
![malloc() and calloc() in C++](https://static.tutorialandexample.com/cpp/malloc-and-calloc-in-cpp2.png)
Need of malloc()
- To allocate memory at runtime, malloc() is used.
- To allocate objects that exist outside of the current block of memory.
- If we need to allocate memory that is greater than the stack size.
Definition of calloc()?
The calloc() function is a built-in library function that means contiguous memory allocation. The calloc() function creates multiple blocks of equal size in memory at runtime. The calloc function is defined in the stdlib.h header file. It has two parameters, the number of blocks and the size of each block. When dynamic memory is allocated using the calloc() function, the base address of the first block is returned, and each block is initialized to 0. If no storage is created, a NULL pointer is returned.
Characteristics of calloc()
- It returns a pointer to the assigned memory block's first byte if the allocation is successful.
- Multiple memory blocks can be assigned using calloc() at a single time
- It deallocates the assigned memory to zero
- It needs size in bytes, so to determine the size, we use sizeof()
Syntax of calloc()
var_name = (data_type *) calloc ( no_of_elements, block_size);
where,
- var_name = the name of the pointer
- data_type = the data type in which we want typecasting to get the pointer of the specified type.
- no_of_elements = total number of blocks
- block_size = size of each block
Types of Return Values for the calloc() Function.
The calloc() function will return:
- If the allocation is successful, a pointer is returned at the first byte of the allocated memory block.
- If the allocation is failed, a null pointer.
Program to illustrate the use of the calloc() function in C++
1. To check the allocation of memory using calloc()
CODE
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int *ptr;
ptr = (int*) calloc (4, sizeof(int));
if (ptr != NULL)
{
cout<<" Memory is created successfully at "<<ptr;
}
else
cout<<" Memory is not created ";
return 0;
}
OUTPUT
![malloc() and calloc() in C++](https://static.tutorialandexample.com/cpp/malloc-and-calloc-in-cpp3.png)
2. To initialize values and store it
CODE
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
if (ptr==NULL) {
cout << "Memory Allocation Failed";
exit(1);
}
else{
cout << "Initializing values..." << endl<< endl;
for (int i = 0; i < 5; i++) {
ptr[i] = i * 3 + 2;
}
}
cout << "The initialized values are: " << endl;
for (int i = 0; i < 5; i++) {
cout << *(ptr + i) << endl;
}
free(ptr);
return 0;
}
OUTPUT
![malloc() and calloc() in C++](https://static.tutorialandexample.com/cpp/malloc-and-calloc-in-cpp4.png)
Need of calloc()
- To make the assigned memory zero.
- When elements are to be initialized to zero to return the pointer to memory.
- To avoid overflow while using malloc().
- To request a page that is already zeroed.