EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

malloc() in C++

Home » Software Development » Software Development Tutorials » C ++ Programming Tutorial » malloc() in C++

malloc() in C++

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.

Syntax

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

void* malloc(size_t size);

Parameters

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.

Popular Course in this category
C++ Training (4 Courses, 5 Projects, 4 Quizzes)4 Online Courses | 5 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access | 4 Quizzes with Solutions
4.5 (4,870 ratings)
Course Price

View Course

Related Courses
Java Training (40 Courses, 29 Projects, 4 Quizzes)C Programming Training (3 Courses, 5 Project)

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:

Example #1

In our first example we will use malloc function to create an array for 6 number of elements of int type:

Code:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int *my_ptr;
my_ptr = (int*) malloc(6*sizeof(int));
if(my_ptr)
{
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;
}
free(my_ptr);
return 0;
}
}

Output:

malloc() in C++1

Example #2

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.

Code:

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
size_t size =0;
int *my_ptr = (int *)malloc(size);
if(my_ptr==NULL)
{
cout << "Null pointer has been returned";
}
else
{
cout << "Memory has been allocated at address" << my_ptr << endl;
}
free(my_ptr);
return 0;
}

Output:

malloc() in C++2

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.

Conclusion

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.

Recommended Articles

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 –

  1. C++ any()
  2. C++ setprecision
  3. Type Casting in C++
  4. Regular Expressions in C++

C++ Training (4 Courses, 5 Projects, 4 Quizzes)

4 Online Courses

5 Hands-on Projects

37+ Hours

Verifiable Certificate of Completion

Lifetime Access

4 Quizzes with Solutions

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C plus plus Programming Tutorial
  • Functions
    • C++ String Functions
    • Math Functions in C++
    • Friend Function in C++
    • Recursive Function in C++
    • Virtual Functions in C++
    • strcat() in C++
    • swap() in C++
    • strcmp() in C++
    • ceil function in C++
    • C++ begin()
    • size() in C++
    • C++ test()
    • C++ any()
    • C++ Bitset
    • C++ find()
    • C++?Aggregation
    • C++?String append
    • C++ String Copy
    • C++ end()
    • C++ endl
    • C++ push_back
    • C++ shuffle()
    • malloc() in C++
    • C++ reserve()
    • C++ unique()
    • C++ sort()
    • C++ find_if()
    • Reflection in C++
    • C++ replace()
    • C++ search()
    • C++ Memset
    • C++ size_t
    • C++ Substring
    • C++ Max
    • C++ absolute value
    • C++ memcpy
    • C++ wchar_t
    • C++ free()
    • C++ sizeof()
    • C++ Move Semantics
  • Basic
    • Introduction To C++
    • What is C++
    • Features of C++
    • Applications of C++
    • Best C++ Compiler
    • C++ Data Types
    • C++ Double
    • C++ unsigned int
    • User Defined Data Types in C++
    • Variables in C++
    • C++ Keywords
    • Pointers in C++
    • C++ Void Pointer
    • Function Pointer in C++
    • Iterator in C++
    • C++ Commands
    • Object in C++
    • C++ Literals
    • C++ Reference
    • C++ Undefined Reference
    • String in C++
    • C++ Programming Language (Basics)
    • C++ Identifiers
    • C++ Header Files
    • Type Casting in C++
    • C++ Formatter
  • Operators
    • C++ Operators
    • Arithmetic Operators in C++
    • Assignment Operators in C++
    • Bitwise Operators in C++
    • Relational Operators in C++
    • Boolean Operators in C++
    • Unary Operators in C++
    • C++ Operator[]
    • Operator Precedence in C++
    • C++ operator=()
  • Control Statements
    • Control Statement in C++
    • if else Statement in C++
    • Else If in C++
    • Nested if in C++
    • Continue Statement in C++
    • Break Statement in C++
    • Switch Statement in C++
    • goto Statement in C++
    • C++ Struct
    • Loops in C++
    • Do While Loop in C++
    • Nested Loop in C++
  • Array
    • Arrays in C++
    • 2D Arrays in C++
    • 3D Arrays in C++
    • Multi-Dimensional Arrays in C++
    • C++ Array Functions
    • String Array in C++
    • C++ Length of Array
    • C++ arraylist
  • Constuctor and Destructor
    • Constructor and Destructor in C++
    • Constructor in C++
    • Destructor in C++
    • Copy Constructor in C++
    • Parameterized Constructor in C++
  • Overloading and overriding
    • Overloading and Overriding in C++
    • Overloading in C++
    • Overriding in C++
    • Function Overloading in C++
    • Function Overriding in C++
    • Method Overloading in C++
  • Inhertiance
    • Types of Inheritance in C++
    • Single Inheritance in C++
    • Multiple Inheritance in C++
    • Hierarchical Inheritance in C++
    • Multilevel Inheritance in C++
    • Hybrid Inheritance in C++
  • Sorting
    • Sorting in C++ 
    • Heap Sort in C++
    • C++ Vector Sort
    • Insertion Sort in C++
    • Selection Sort in C++
  • Advanced
    • C++ namespace
    • Encapsulation in C++
    • Access Modifiers in C++
    • Abstract Class in C++
    • C++ Class and Object
    • What is Template Class in C++?
    • C++ Algorithm
    • Data Structures and Algorithms C++
    • C++ Garbage Collection
    • Virtual Keyword in C++
    • Access Specifiers in C++
    • Storage Class in C++
    • Call by Value in C++
    • Multimap in C++
    • C++ Multiset
    • C++ Lambda Expressions
    • Stack in C++
    • C++ Static
    • C++ static_cast
    • Deque in C++
    • C++ Vector Functions
    • C++ 2D Vector
    • C++ List
    • C++ Mutable
    • Enum in C++
    • Abstraction in C++
    • Signal in C++
    • C++ Queue
    • Priority Queue in C++
    • Regular Expressions in C++
    • C++ Hash Table
    • File Handling in C++
    • C++ Stream
    • ifstream in C++
    • C++ ofstream
    • C++ fstream
    • C++ Read File
    • C++ iomanip
    • Macros in C++
    • Templates in C++
    • C++ setprecision
    • C++ Int to String
    • C++ thread( )
    • C++ Thread Pool
    • C++ thread_local
  • Programs
    • Patterns in C++
    • Star Patterns In c++
    • Swapping in C++
    • Reverse Number in C++
    • Palindrome Program in C++
    • Palindrome in C++
    • Factorial Program in C++
    • Fibonacci Series in C++
    • Square Root in C++
    • Random Number Generator in C++
    • Prime Number in C++
    • Leap Year Program in C++
    • Anagram in C++
    • Armstrong Number in C++
    • Reverse String in C++
    • Socket Programming in C++
    • Matrix Multiplication in C++
    • C++ using vs typedef
    • C++ vector vs list
    • C++ vector vs array
  • Interview question
    • C++ Interview Questions
    • Multithreading Interview Questions C++

Related Courses

C++ Training Course

Java Training Course

C Programming Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C++ Training (4 Courses, 5 Projects, 4 Quizzes) Learn More