• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C++ » Pointer » Write A C++ Program To Use Malloc To Allocate Memory.
Next →
← Prev

Write A C++ Program To Use Malloc To Allocate Memory.

By Dinesh Thakur

The function malloc () of header file <stdlib.h> allocates memory of size (in bytes) expressed as its argument. The return value of malloc () is a void pointer to the first byte of the allocated block of memory. However, if the process of allocation of memory fails due to lack of sufficient memory, or due to some other reason, it returns NULL pointer. The argument of malloc () is the unsigned integer or an expression which evaluates to an unsigned integer. Any program using this function should also have statements which check the return value of the function so that if the memory is not available one can gracefully exit from the program.

Since the function malloc () returns a void pointer, it has to be cast to the type of data being dealt with. The header file <stdlib. h> must be included in the program if you are using malloc (). The prototype of the function is given below.

void* malloc(size_t size);

In the above declaration, size_t is the typedef of unsigned integer number. For allocating memory for variables of types int, double, char etc., we must cast the void pointer returned by malloc ( ) to the ‘respective type. For instance, say we want to allocate memory to store n integers in contiguous memory locations like elements of an array, the code may be written as given below.

# include <stdlib.h>

   int *ptri ;

   ptri = (int*) malloc(n*sizeof(int));

In the above code, the function malloc allocates n*sizeof (int) bytes of memory and returns the value of pointer ptri. For example, the following code will allocate enough memory to store two int numbers. The return value of the function malloc is the value of ptri which is the address of the first byte of the memory block.

Suppose that the system allocates 4 bytes for storing one int number, then for storing 2 int numbers, the above expression will allocate 4 x 2 = 8 bytes of memory and will return the address of the first byte of this chunk of memory. That address would represent the value of pointer ptri. In case the allocation is not successful due to lack of available memory, the return value would be NULL pointer. Therefore,

for the above code the following test should also be included for graceful exit:

if ( ptri == NULL)

  printf(“Error in memory allocation”);

  exit(1);

As a second example, let us consider that we need to allocate enough memory to store m double numbers. The code is as below.

double *pd ;

pd= (double*) malloc( m* sizeof(double));

Similarly, we may use this function in creating arrays of structures in linked lists. Suppose, we have structures of the following type:

struct Student

{

  char Name [30];

  int grade;

};

If it is required to dynamically create n such structures, the memory allocation for the n structures

may be done as follows:

struct student * Pst;

Pst = (struct Student*) malloc( n* sizeof(struct Student));

Illustrates allocation of memory for an array by malloc () .

#include<conio.h> 
#include <iostream.h>
#include <stdlib.h>
void main()
{
       char *p;
       clrscr();
       p = (char*) malloc(8);
       if(!p )
         {
                     cout<<"Memory Allocation Failed";
                     exit(1);
           }
                     cout<<"Enter a String: ";
                     cin.get(p,80);
                     cout<<p;
                     free(p);
                     getch();
}

Use Malloc To Allocate Memory

You’ll also like:

  1. Write A C++ Program To Allocate Memory And Reallocate.
  2. How to Creating Objects and Allocate Memory for Objects in c++
  3. Write a C++ Program for Memory allocation for a class
  4. C program to Allocate space dynamically for the array
  5. Write a Program to Create a Structure of N Students using Dynamic Memory Allocation. Read their Names & Print the Result
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C++ Tutorials

C++ Tutorials

  • C++ - Data Types
  • C++ - Operators Types
  • C++ - CPP Program Structure
  • C++ - Conditional Statements
  • C++ - Loop
  • C++ - do-While Loop
  • C++ - Control Statements
  • C++ - Tokens
  • C++ - Jump Statements
  • C++ - Expressions
  • C++ - Constants
  • C++ - Character Set
  • C++ - Iteration Statements
  • C++ - I/O Statements
  • C++ - String
  • C++ - Manipulators

C++ Operator

  • C++ - Input/Output Operator
  • C++ - Operator Overloading

C++ Functions

  • C++ - Functions
  • C++ - Member Functions
  • C++ - Returning Object from Function
  • C++ - Call by Value Vs Reference
  • C++ - Friend Function
  • C++ - Virtual Function
  • C++ - Inline Function
  • C++ - Static Data Members
  • C++ - Static Member Functions

C++ Array & Pointer

  • C++ - Array
  • C++ - Array of Objects
  • C++ - Arrays as Class Members
  • C++ - Vector
  • C++ - Pointer
  • C++ - 'this' Pointer

C++ Classes & Objects

  • C++ - Class
  • C++ - Program Structure With Classes
  • C++ - OOP’s
  • C++ - Objects as Function Arguments
  • C++ - Procedure Vs OOL
  • C++ - Object Vs Class
  • C++ - Creating Objects
  • C++ - Constructors
  • C++ - Copy Constructor
  • C++ - Constructor Overloading
  • C++ - Destructor
  • C++ - Polymorphism
  • C++ - Virtual Base Class
  • C++ - Encapsulation

C++ Inheritance

  • C++ - Inheritance
  • C++ - Multiple Inheritance
  • C++ - Hybrid Inheritance
  • C++ - Abstraction
  • C++ - Overloading

C++ Exception Handling

  • C++ - Exception Handling
  • C++ - Templates
  • C++ - Standard Template Library

C++ Data Structure

  • C++ - Link List

C++ Programs

  • C++ Program for Electricity Bill
  • C++ Program for Multiply Matrices
  • C++ Program for Arithmetic Operators
  • C++ Program For Matrices
  • C++ Program for Constructor
  • C++ Program Verify Number
  • C++ Program Array Of Structure
  • C++ Program to find Average Marks
  • C++ Program Add And Subtract Matrices
  • C++ Program Menu Driven
  • C++ Program To Simple Interest
  • C++ Program To Find Average
  • C++ program exit()
  • C++ Program Using Array Of Objects
  • C++ Program Private Member Function
  • C++ Program To Reverse A String
  • C++ Program to Operator Overloading

Other Links

  • C++ - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW