Malloc in C++

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The malloc is the short name for memory allocation. A Malloc function is included in the <cstdlib> header in a C++ library. The malloc function is used in C++ to allocate dynamically uninitialized memory blocks of a specified size to variables.

The syntax for the malloc is given below :

Syntax of Malloc in c++

The syntax for malloc() is given below:

In the syntax above size refers to the amount of memory (in bytes) we want to allocate.

Parameters of Malloc in C++

Calling the malloc function only requires one parameter: the size of the memory block to be allocated. this parameter is of size_t type.

The malloc() function requires the following parameters:

  • size - This value represents the size of a memory block in bytes.
  • size_t - This value is cast from the size parameter only, representing the unsigned integral type.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Return Value of Malloc in C++

The malloc() function returns:

  1. If memory allocation as per the size indicated in the heap succeeds then, the return value is a pointer pointing to the first byte of the memory block allocated by the function.
  2. If function fails that is (if memory allocation fails) then the malloc() returns null pointer.

But make a note that as soon as the size is zero, the value is dependent on the implementation of the library. The value may or may not point to null.

Exceptions for Malloc in C++

There is no exception thrown by the malloc() function.

What is Malloc in C++

How malloc() Function Works?

malloc function works

A malloc function is included in the <cstdlib> header in a C++ library. malloc() is used to allocate a contiguous memory block to a variable or array on a heap according to the size specified. Upon calling this method for a size_t variable, the compiler searches on the heap for a memory block of the same size and returns a void pointer to the memory block's starting address.

Turn Learning into Career Growth

1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary
1200+Hiring Partners
89%Placement Rate
11,000+Placements
147%Avg Salary Increment
2.5XCareer Growth
₹23 LPAAvg Post-Scaler Salary

Why malloc() Returns Void Pointer?

The pointer returned by malloc() has no idea where it is pointing to. malloc() just allocates memory based on a request by the user without knowing what type of data is to be stored in the memory. Therefore the pointer returned is void by malloc(), since the pointer returned is void any appropriate datatype can be typecasted to the void pointer easily.

But as soon as a memory block is assigned to a size of 0, a NULL pointer is returned, which behaves as an indeterminate pointer and shall not be dereferenced.

How does malloc() Operate?

malloc operate In the above example, the 3 bytes of memory in the heap are allocated and the address of 1^st^ byte out of 3 is stored in the pointer named ptr. At the same time while malloc() returns a void pointer, the user has already specified its type as int and hence the void pointer is typecast into an integer.

Note: The size_t variable is defined in the standard library <stdlib.h> as an unsigned int.

Examples

1. Malloc in C++ with Size Zero

Code:

Output:

Explanation:

In the above program, we are using malloc() for allocating int memory having size 0 pointing to the pointer ptr. Here we are using the if statement to check if pointer ptr pointed to NULL or memory. If ptr points to NULL the print statement inside the if statement prints "Pointed to null pointer" otherwise else is executed where the memory address of the memory block allocated in the heap gets printed as output.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data

2. Using malloc() to Create an Array for 5 Integers.

code:

Output:

Explanation:

In the above program, we use malloc() to allocate 5 blocks of int memory to the pointer ptr for storing odd digits. Therefore, now the ptr acts like an array. Now, first, we typecast the void pointer into an integer. Then using a for loop, we initialize five memory blocks to hold the first five odd numbers. Using the second for loop we print the actual values of the odd number. At last, we deallocate the memory using free(ptr);.

Conclusion

Let's conclude what we have learned in this tutorial :

  • With the malloc method, memory is allocated dynamically to variables in the form of an array and a void pointer is returned pointing to the starting address for the memory block.
  • Since the pointer returned is void by malloc() any appropriate datatype can be typecasted to the void pointer easily.
  • There is no exception thrown by the malloc() function.
  • Calling the malloc method only requires one parameter: the size of the memory block to be allocated.
  • The size_t variable is defined in the standard library <stdlib.h> as an unsigned int.
  • We use free(ptr); for deallocation of memory;

See Also

Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more