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.
Syntax:
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.
Syntax of malloc()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()
Example 1:
C++
// C++ program to demonstrate working of malloc()
// cstdlib is used to use malloc function
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
// size_t is an integer data type which can assign
// greater than or equal to 0 integer values
size_t s = 0; // s is SIZE
// malloc declaration/initialization
int* ptr = (int*)malloc(s);
// return condition if the memory block is not
// initialized
if (ptr == NULL) {
cout << "Null pointer has been returned";
}
// condition printing the message if the memory is
// initialized
else {
cout << "Memory has been allocated at address "
<< ptr << endl;
}
free(ptr);
return 0;
}
OutputMemory has been allocated at address 0x8cae70
free() function in C++ is used to dynamically de-allocate the memory.
Example 2:
C++
// C++ program to demonstrate working of malloc()
#include <iostream>
#include<stdlib.h>
using namespace std;
int main()
{
// variable declaration
int var_len = 10;
// pointer variable declaration
int *ptr;
// allocating memory to the pointer variable using malloc()
ptr = (int*) malloc(sizeof(int)*var_len);
for(int i=0;i<var_len;i++)
{
cout << "Enter a number : " << endl;
cin >> *(ptr+i);
}
cout << "Entered elements are : " << endl;
for(int i=0;i<var_len;i++)
{
cout << *(ptr+i) << endl;
}
free(ptr);
return 0;
}
Output:
Output of malloc() initializationWhere 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
Variables or Arrays created using malloc exist for a lifetime until they are cleared. This is of great importance for various data structures such as linked lists, binary heap, etc.
Difference between new and malloc()
new | 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 |
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is
15 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() In C, a variable defined in a function is stored in the stack memory. The requirement of this memory is that it needs to know the size of the data to memory at compile time (before the program runs). Also, once defined, we can neither change the size nor completely delete the memory.To resolve this,
9 min read
Vector in C++ STL C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Templates in C++ C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
C++ Interview Questions and Answers (2025) C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read
Operator Overloading in C++ in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot
8 min read
C++ Classes and Objects In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. We will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program.C++ ClassesA class is a user-defined data type, which holds its own data members and
9 min read