SlideShare a Scribd company logo
4
Most read
18
Most read
24
Most read
Memory Management in C++
Peeling operator new() and delete()
Sameer Singh Rathoud
About presentation
This presentation will help reader in understanding some basic concept of dynamic
memory management in C++.
operator new() and delete()
operator “new()” and “delete()” are the built-in language support for
dynamically allocation and de-allocation of memory In C++.
About operator new()
• Operator “new()” can be user defined or built-in.
• If a programmer don’t specify operator “new()”, built-in operator
“new()” will be used by default.
• Operator “new()” can be defined globally or as a member of class.
• There should be only one global operator “new()” with particular types of
parameter in an executable.

• Operator “new()” global/local only allocates the memory from heap.
• Memory allocated on heap is having lifespan beyond its original scope.

So to prevent the memory from leaking, programmer explicitly need to
release the memory
Advantages of new()
Programmer don’t need to define the size of (“sizeof”) memory to allocate while
using operator “new()”.

Provide flexibility to the programmer to overload the operator “new()” as per
need.
• Improves code readability.

• No need of casting explicitly.
• Returns null pointer on failure and provide flexibility to the user to handle the
scenario.
Minimal definition of operator new()
extern "C" void *malloc (size_t);
void* operator new(size_t sz) {
return malloc (sz);
}
class A {
};
int main() {
A *a = new A();
return 0;
}

This is the minimal definition of operator
“new()” taking the argument as size of
memory to be allocated and returning the
void* of the memory allocated by “malloc”.
Handling new() failure
A Programmer can handle failure of
operator “new()” in two ways:
• Programmer can use “nothrow”
option and check for the null
pointer.
• Programmer can use “try –
catch”
block
to
catch
“std::bad_alloc exception”.

Method 1:
A *p_a = new(nothrow) A();
If(!p_a)
{
// new() failure handling
}
Method 2:
try {
A *p_a = new A();
}
catch(std::bad_alloc& ex) {
// new() failure handling
}
Handling new() failure -

_new_handler and set_new_handler

• If operator “new()” fails to find memory it calls pointer to a function
“_new_handler()”.

• If “_new_handler()” again fails to find memory it throws “std::bad_alloc
exception”.
• A

programmer

can

set

“set_new_handler()”.

his

own

“_new_handler”

using

function
Handling new() failure -

_new_handler

“_new_handler()” example
void _new_handler() {
cout << "Failed to allocate memory" << endl;
exit(1);
}
extern "C" void *malloc (size_t);
void *operator new (size_t size) {
void *p = NULL;
while ((p = malloc (size)) == 0)
if (_new_handler)
(*_new_handler)();
else
return 0;
return p;
}
Handling new() failure -

set_new_handler

“set_new_handler()” example
void newFailed() {
cout << "Failed to allocate memory" << endl;
exit(1);
}

int main() {
set_new_handler(newFailed);
A *p_a = new A();
return 0;
}
malloc() and free() with C++
A programmer can use “malloc()” and “free()” routines with C++

Caution:
• Never mix “new()” with “free()” or “malloc()” with “delete()”.
• Always remember “malloc()” and “free()” do not call constructor and
destructor. So be careful to use these routines with class objects.

C++ doesn’t support “realloc()” like operator.
Allocation and de-allocation of array
• Operator “new()” and “delete()” can also be used for allocating and deallocating of memory for array of objects.
• When calling the operator “delete()” for the pointer to an array, a
programmer has to use [] with “delete()” to free entire array’s memory.

A *p_a1 = new A();
A *p_a2 = new A[10];
delete p_a1; // deleting object
delete[] p_a2; // deleting array of object
Construction and destruction
Construction of an object happens in 3 steps:
• Allocate the sufficient memory to hold the object.
• If allocation is successful call the constructor and create an object in that
memory.
• Store the address of the allocated memory in the specified pointer.
A *p_a = new A();
• Allocate the sufficient memory to hold the object of class A.
• If allocation is successful call A() and create an object of A in that memory.

• Store the address of the allocated memory in p_a.
Construction and destruction continue …
delete p_a;
Destruction of an object happens in 2 steps:
• Call the destructor of A (~A())
• De-allocate the memory pointed by p_a;
Construction and destruction continue …
• Allocation and de-allocation of memory is handled by operator “new()”
and “delete()”.
• Construction and destruction of an object is handled by constructor
and destructor.
• Before invocation of constructor memory has been already allocated
for the object, so that constructor can do its work.
• Destructor only destructs the object and not responsible for cleaning
up the memory and after destructor completes its job then only

memory will get cleaned up.
Object placement syntax
• As default operator “new()” allocates the memory from the pool of free
memory (heap).
Always this might not be the requirement. May be user wanted to create an object
at any specific location (e.g. in case of shared memory).
• As the solution of this C++ provides default placement version of operator
“new()”, to create an object at specified location.
void *operator new() (size_t, void *p) { return p; }
Object placement syntax continue …
Usage:
void* vp_a = shm_malloc (sizeof (A)); // allocate memory in shared memory
A* p_a = new() (vp_a) A; // construct a “A” object there.

As we have constructed an object in the memory already got allocated, we need a
way to destroy the object without releasing the memory.
p_a->(~A());
shm_free(p_a);
Object placement syntax continue …
Placement syntax can also be used to pass additional parameters.
Placement syntax can be used to resize the allocated memory, but can only be
used for built-in types, because of object construction and destruction issues
and highly not recommended.
Class specific operator new() and delete()
A programmer can specify a class specific operator “new()” and “delete()”.

class A {
public:
void* operator new(size_t);
void operator delete(void*);
};

Now “A::operator
instead

of

global

new()” will be used
operator

“new()”.

The

specified version of operator “new()” will only

be work for class A and classes derived from A.
It won’t be used for array of objects, as we

have not specified the array version of operator
“new()”.
void* operator new[](size_t);
Overloading operator new() and delete()
• A programmer can specify any number of overloaded operator “new()” with
different signature.

• It is not possible to overload operator “delete()” with different signature.
• Class specific overloaded operator “new()” and “delete()” obeys the same

scope rule as other member functions of class.
• And class specific operator “new()” and “delete()” will hide the global
operator “new()” and “delete()”, which may give error in case of incorrect
usage (like no operator “new()” found for class with specified signature).
class A {
public:
void* operator new(size_t, int);
};
A* p_a = new() A; // will get error
Overloading operator new() and delete() continue …
A programmer can solve thus problem in few ways.
• Define a class specific default operator “new()”.
• Can explicitly give call to global operator
“new()”.

Method 1:
class A {
public:
void* operator new(size_t,
int);
void* operator new(size_t);
};
A* p_a = new() A;

• Can give the default value to the argument.
Method 2:
A* p_a = ::new() A;

Method 3:
class A {
public:
void* operator new(size_t,
int i = 0);
};
A* p_a = new() A;
Variants of built-in operator new() and delete()
• void* operator new(std::size_t) throw (std::bad_alloc);
• void* operator new[](std::size_t) throw (std::bad_alloc);
• void operator delete(void*) throw();
• void operator delete[](void*) throw();
• void* operator new(std::size_t, const std::nothrow_t&) throw();

• void* operator new[](std::size_t, const std::nothrow_t&) throw();
• void operator delete(void*, const std::nothrow_t&) throw();

• void operator delete[](void*, const std::nothrow_t&) throw();
Variants of built-in operator new() and delete() continue …
• inline void* operator new(std::size_t, void* __p) throw() { return __p; }

• inline void* operator new[](std::size_t, void* __p) throw() { return __p; }
• inline void operator delete (void*, void*) throw() { }

• inline void operator delete[](void*, void*) throw() { }
End of Presentation . . .

More Related Content

What's hot (20)

PDF
Polymorphism In Java
Spotle.ai
 
PDF
C++ Files and Streams
Ahmed Farag
 
PPSX
Type conversion
Frijo Francis
 
PPTX
Advanced Python : Decorators
Bhanwar Singh Meena
 
PPTX
Destructors
DeepikaT13
 
PPSX
Exception Handling
Reddhi Basu
 
PPS
Java Exception handling
kamal kotecha
 
PDF
Java exception handling ppt
JavabynataraJ
 
PPTX
Infix to postfix conversion
Then Murugeshwari
 
PPTX
Inheritance in java
RahulAnanda1
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PPT
Function overloading(c++)
Ritika Sharma
 
PPTX
Exception handling c++
Jayant Dalvi
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPTX
Recursive Function
Harsh Pathak
 
PDF
Function overloading ppt
Prof. Dr. K. Adisesha
 
PPTX
Presentation on pointer.
Md. Afif Al Mamun
 
PPTX
Oop c++class(final).ppt
Alok Kumar
 
PPTX
Python Functions
Mohammed Sikander
 
PPT
Java Notes
Abhishek Khune
 
Polymorphism In Java
Spotle.ai
 
C++ Files and Streams
Ahmed Farag
 
Type conversion
Frijo Francis
 
Advanced Python : Decorators
Bhanwar Singh Meena
 
Destructors
DeepikaT13
 
Exception Handling
Reddhi Basu
 
Java Exception handling
kamal kotecha
 
Java exception handling ppt
JavabynataraJ
 
Infix to postfix conversion
Then Murugeshwari
 
Inheritance in java
RahulAnanda1
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Function overloading(c++)
Ritika Sharma
 
Exception handling c++
Jayant Dalvi
 
Pointer in C++
Mauryasuraj98
 
Recursive Function
Harsh Pathak
 
Function overloading ppt
Prof. Dr. K. Adisesha
 
Presentation on pointer.
Md. Afif Al Mamun
 
Oop c++class(final).ppt
Alok Kumar
 
Python Functions
Mohammed Sikander
 
Java Notes
Abhishek Khune
 

Similar to Memory Management C++ (Peeling operator new() and delete()) (20)

PPTX
ADK COLEGE.pptx
Ashirwad2
 
PPT
C++ Memory Management
Anil Bapat
 
PDF
Dynamics allocation
Kumar
 
PPT
dynamic-memory-management-in-c-and-c++.ppt
SuwoebBeisvs
 
PPTX
Memory management
sana younas
 
PPT
Memory Management In C++
ShriKant Vashishtha
 
PPT
16858 memory management2
Aanand Singh
 
PPTX
Dynamic memory allocation in c++
Tech_MX
 
PPT
Pointer
manish840
 
PDF
CS225_Prelecture_Notes 2nd
Edward Chen
 
PDF
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
PPT
memory
teach4uin
 
PPTX
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
PPTX
PPT DMA.pptx
Abhishekkumarsingh630054
 
PPTX
C++ Introduction brown bag
Jacob Green
 
PPT
16829 memory management2
Sidharth Sundaresan
 
PPTX
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
ChetanRaut43
 
PPTX
C++.pptx
Sabi995708
 
PPTX
OBJECT ORIENTED PROGRAMMING using C++ / CPP
RAKSHITDOGRA1
 
PPTX
Constructors and Destructors
Keyur Vadodariya
 
ADK COLEGE.pptx
Ashirwad2
 
C++ Memory Management
Anil Bapat
 
Dynamics allocation
Kumar
 
dynamic-memory-management-in-c-and-c++.ppt
SuwoebBeisvs
 
Memory management
sana younas
 
Memory Management In C++
ShriKant Vashishtha
 
16858 memory management2
Aanand Singh
 
Dynamic memory allocation in c++
Tech_MX
 
Pointer
manish840
 
CS225_Prelecture_Notes 2nd
Edward Chen
 
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
memory
teach4uin
 
Data structure and Algorithms (C++).pptx
ammarasalmanqureshi7
 
C++ Introduction brown bag
Jacob Green
 
16829 memory management2
Sidharth Sundaresan
 
C++ MEMORY MANAGEMENT.pptx/ kbibuvvw veovn nveknev ovne onv
ChetanRaut43
 
C++.pptx
Sabi995708
 
OBJECT ORIENTED PROGRAMMING using C++ / CPP
RAKSHITDOGRA1
 
Constructors and Destructors
Keyur Vadodariya
 
Ad

More from Sameer Rathoud (8)

PDF
Platformonomics
Sameer Rathoud
 
PDF
AreWePreparedForIoT
Sameer Rathoud
 
PDF
Observer design pattern
Sameer Rathoud
 
PDF
Decorator design pattern (A Gift Wrapper)
Sameer Rathoud
 
PDF
Proxy design pattern (Class Ambassador)
Sameer Rathoud
 
PDF
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
PDF
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
PPTX
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 
Platformonomics
Sameer Rathoud
 
AreWePreparedForIoT
Sameer Rathoud
 
Observer design pattern
Sameer Rathoud
 
Decorator design pattern (A Gift Wrapper)
Sameer Rathoud
 
Proxy design pattern (Class Ambassador)
Sameer Rathoud
 
Builder Design Pattern (Generic Construction -Different Representation)
Sameer Rathoud
 
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
Singleton Pattern (Sole Object with Global Access)
Sameer Rathoud
 
Ad

Recently uploaded (20)

PDF
July Patch Tuesday
Ivanti
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
July Patch Tuesday
Ivanti
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Biography of Daniel Podor.pdf
Daniel Podor
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 

Memory Management C++ (Peeling operator new() and delete())

  • 1. Memory Management in C++ Peeling operator new() and delete() Sameer Singh Rathoud
  • 2. About presentation This presentation will help reader in understanding some basic concept of dynamic memory management in C++.
  • 3. operator new() and delete() operator “new()” and “delete()” are the built-in language support for dynamically allocation and de-allocation of memory In C++.
  • 4. About operator new() • Operator “new()” can be user defined or built-in. • If a programmer don’t specify operator “new()”, built-in operator “new()” will be used by default. • Operator “new()” can be defined globally or as a member of class. • There should be only one global operator “new()” with particular types of parameter in an executable. • Operator “new()” global/local only allocates the memory from heap. • Memory allocated on heap is having lifespan beyond its original scope. So to prevent the memory from leaking, programmer explicitly need to release the memory
  • 5. Advantages of new() Programmer don’t need to define the size of (“sizeof”) memory to allocate while using operator “new()”. Provide flexibility to the programmer to overload the operator “new()” as per need. • Improves code readability. • No need of casting explicitly. • Returns null pointer on failure and provide flexibility to the user to handle the scenario.
  • 6. Minimal definition of operator new() extern "C" void *malloc (size_t); void* operator new(size_t sz) { return malloc (sz); } class A { }; int main() { A *a = new A(); return 0; } This is the minimal definition of operator “new()” taking the argument as size of memory to be allocated and returning the void* of the memory allocated by “malloc”.
  • 7. Handling new() failure A Programmer can handle failure of operator “new()” in two ways: • Programmer can use “nothrow” option and check for the null pointer. • Programmer can use “try – catch” block to catch “std::bad_alloc exception”. Method 1: A *p_a = new(nothrow) A(); If(!p_a) { // new() failure handling } Method 2: try { A *p_a = new A(); } catch(std::bad_alloc& ex) { // new() failure handling }
  • 8. Handling new() failure - _new_handler and set_new_handler • If operator “new()” fails to find memory it calls pointer to a function “_new_handler()”. • If “_new_handler()” again fails to find memory it throws “std::bad_alloc exception”. • A programmer can set “set_new_handler()”. his own “_new_handler” using function
  • 9. Handling new() failure - _new_handler “_new_handler()” example void _new_handler() { cout << "Failed to allocate memory" << endl; exit(1); } extern "C" void *malloc (size_t); void *operator new (size_t size) { void *p = NULL; while ((p = malloc (size)) == 0) if (_new_handler) (*_new_handler)(); else return 0; return p; }
  • 10. Handling new() failure - set_new_handler “set_new_handler()” example void newFailed() { cout << "Failed to allocate memory" << endl; exit(1); } int main() { set_new_handler(newFailed); A *p_a = new A(); return 0; }
  • 11. malloc() and free() with C++ A programmer can use “malloc()” and “free()” routines with C++ Caution: • Never mix “new()” with “free()” or “malloc()” with “delete()”. • Always remember “malloc()” and “free()” do not call constructor and destructor. So be careful to use these routines with class objects. C++ doesn’t support “realloc()” like operator.
  • 12. Allocation and de-allocation of array • Operator “new()” and “delete()” can also be used for allocating and deallocating of memory for array of objects. • When calling the operator “delete()” for the pointer to an array, a programmer has to use [] with “delete()” to free entire array’s memory. A *p_a1 = new A(); A *p_a2 = new A[10]; delete p_a1; // deleting object delete[] p_a2; // deleting array of object
  • 13. Construction and destruction Construction of an object happens in 3 steps: • Allocate the sufficient memory to hold the object. • If allocation is successful call the constructor and create an object in that memory. • Store the address of the allocated memory in the specified pointer. A *p_a = new A(); • Allocate the sufficient memory to hold the object of class A. • If allocation is successful call A() and create an object of A in that memory. • Store the address of the allocated memory in p_a.
  • 14. Construction and destruction continue … delete p_a; Destruction of an object happens in 2 steps: • Call the destructor of A (~A()) • De-allocate the memory pointed by p_a;
  • 15. Construction and destruction continue … • Allocation and de-allocation of memory is handled by operator “new()” and “delete()”. • Construction and destruction of an object is handled by constructor and destructor. • Before invocation of constructor memory has been already allocated for the object, so that constructor can do its work. • Destructor only destructs the object and not responsible for cleaning up the memory and after destructor completes its job then only memory will get cleaned up.
  • 16. Object placement syntax • As default operator “new()” allocates the memory from the pool of free memory (heap). Always this might not be the requirement. May be user wanted to create an object at any specific location (e.g. in case of shared memory). • As the solution of this C++ provides default placement version of operator “new()”, to create an object at specified location. void *operator new() (size_t, void *p) { return p; }
  • 17. Object placement syntax continue … Usage: void* vp_a = shm_malloc (sizeof (A)); // allocate memory in shared memory A* p_a = new() (vp_a) A; // construct a “A” object there. As we have constructed an object in the memory already got allocated, we need a way to destroy the object without releasing the memory. p_a->(~A()); shm_free(p_a);
  • 18. Object placement syntax continue … Placement syntax can also be used to pass additional parameters. Placement syntax can be used to resize the allocated memory, but can only be used for built-in types, because of object construction and destruction issues and highly not recommended.
  • 19. Class specific operator new() and delete() A programmer can specify a class specific operator “new()” and “delete()”. class A { public: void* operator new(size_t); void operator delete(void*); }; Now “A::operator instead of global new()” will be used operator “new()”. The specified version of operator “new()” will only be work for class A and classes derived from A. It won’t be used for array of objects, as we have not specified the array version of operator “new()”. void* operator new[](size_t);
  • 20. Overloading operator new() and delete() • A programmer can specify any number of overloaded operator “new()” with different signature. • It is not possible to overload operator “delete()” with different signature. • Class specific overloaded operator “new()” and “delete()” obeys the same scope rule as other member functions of class. • And class specific operator “new()” and “delete()” will hide the global operator “new()” and “delete()”, which may give error in case of incorrect usage (like no operator “new()” found for class with specified signature). class A { public: void* operator new(size_t, int); }; A* p_a = new() A; // will get error
  • 21. Overloading operator new() and delete() continue … A programmer can solve thus problem in few ways. • Define a class specific default operator “new()”. • Can explicitly give call to global operator “new()”. Method 1: class A { public: void* operator new(size_t, int); void* operator new(size_t); }; A* p_a = new() A; • Can give the default value to the argument. Method 2: A* p_a = ::new() A; Method 3: class A { public: void* operator new(size_t, int i = 0); }; A* p_a = new() A;
  • 22. Variants of built-in operator new() and delete() • void* operator new(std::size_t) throw (std::bad_alloc); • void* operator new[](std::size_t) throw (std::bad_alloc); • void operator delete(void*) throw(); • void operator delete[](void*) throw(); • void* operator new(std::size_t, const std::nothrow_t&) throw(); • void* operator new[](std::size_t, const std::nothrow_t&) throw(); • void operator delete(void*, const std::nothrow_t&) throw(); • void operator delete[](void*, const std::nothrow_t&) throw();
  • 23. Variants of built-in operator new() and delete() continue … • inline void* operator new(std::size_t, void* __p) throw() { return __p; } • inline void* operator new[](std::size_t, void* __p) throw() { return __p; } • inline void operator delete (void*, void*) throw() { } • inline void operator delete[](void*, void*) throw() { }