SlideShare a Scribd company logo
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 . . .
Ad

More Related Content

What's hot (20)

Constructors in C++
Constructors in C++Constructors in C++
Constructors in C++
RubaNagarajan
 
Types of Constructor in C++
Types of Constructor in C++Types of Constructor in C++
Types of Constructor in C++
Bhavik Vashi
 
C++
C++C++
C++
VishalMishra313
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
SudhanshuVijay3
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
C functions
C functionsC functions
C functions
University of Potsdam
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
Ahmed Farag
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
Harsh Patel
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Files in c++
Files in c++Files in c++
Files in c++
Selvin Josy Bai Somu
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
C++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming languageC++ Class & object pointer in c++ programming language
C++ Class & object pointer in c++ programming language
HariTharshiniBscIT1
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
Haresh Jaiswal
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
Vraj Patel
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
rajveer_Pannu
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 

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

Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
ShriKant Vashishtha
 
PPT DMA.pptx
PPT  DMA.pptxPPT  DMA.pptx
PPT DMA.pptx
Abhishekkumarsingh630054
 
16829 memory management2
16829 memory management216829 memory management2
16829 memory management2
Sidharth Sundaresan
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
Aanand Singh
 
Devry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newDevry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory new
williamethan912
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
memory
memorymemory
memory
teach4uin
 
Virtual Method Table and accident prevention
Virtual Method Table and accident preventionVirtual Method Table and accident prevention
Virtual Method Table and accident prevention
Andrey Karpov
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
Karthik Sekar
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detection
Võ Hòa
 
One Careful Owner
One Careful OwnerOne Careful Owner
One Careful Owner
Kevlin Henney
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
Nico Ludwig
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Anil Bapat
 
W3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptW3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascript
Changhwan Yi
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
Connex
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
karmuhtam
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
helpme43
 
16858 memory management2
16858 memory management216858 memory management2
16858 memory management2
Aanand Singh
 
Devry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory newDevry gsp 215 week 6 i lab virtual memory new
Devry gsp 215 week 6 i lab virtual memory new
williamethan912
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
Keyur Vadodariya
 
Virtual Method Table and accident prevention
Virtual Method Table and accident preventionVirtual Method Table and accident prevention
Virtual Method Table and accident prevention
Andrey Karpov
 
Constructor destructor.ppt
Constructor destructor.pptConstructor destructor.ppt
Constructor destructor.ppt
Karthik Sekar
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detection
Võ Hòa
 
(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings(5) cpp dynamic memory_arrays_and_c-strings
(5) cpp dynamic memory_arrays_and_c-strings
Nico Ludwig
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
Anil Bapat
 
W3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascriptW3C HTML5 KIG-How to write low garbage real-time javascript
W3C HTML5 KIG-How to write low garbage real-time javascript
Changhwan Yi
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
Connex
 
Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
karmuhtam
 
PF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptxPF UE LEC 7 Pointers programming fundamentals (2).pptx
PF UE LEC 7 Pointers programming fundamentals (2).pptx
helpme43
 
Ad

More from Sameer Rathoud (8)

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

Recently uploaded (20)

TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 

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() { }