Explicit Memory Management

Contents[Show]

Explicit memory management has in C++ a high complexity but also provides a great functionality. Sad to say, but this special domain in not so known in C++. For example, you can directly create objects in static memory, in a reserved area, or even in a memory pool. That is functionality, that is often key in safety critical applications in the embedded world. Before the harvest is the work. Therefore, I will give in this post an overview, before I dive deeper into the details.

 

In C++ we use new and new[] for memory allocation and delete and delete[] for memory deallocation. But that is by far not the whole story.

Memory allocation

new

Thanks to the operator new you can dynamically allocate memory for the instance of a type.

int* i= new int;
double* x= new double(10.0);
Circle* c= new Circle;
Point* p= new Point(1.0, 2.0);

 

The in round brackets used arguments are the arguments for the constructor. The result of the new call is a pointer to the according type. The initialization of the instance is happing after the allocation of the memory. Placement new uses the fact, that new consists of two steps. If the object is object of a class hierarchy, the constructors of all base classes will automatically be performed

new[]

new[] creates in opposite to new a C array of objects. The newly created objects need a default constructor.

double* da= new double[5];
Circle* ca= new Circle[8];

Placement new

Placement new is often used to instantiate an object in a pre reserved memory area. In addition, you can overload placement new globally and for own data types. This is the big benefit that C++ offer.

1
2
3
4
5
char* memory= new char[sizeof(Account)];
Account* a= new(memory) Account;

char* memory2= new char[5*sizeof(Account)];
Account* b= new(memory2) Account[5];

 

Placement new needs an additional argument (line 2 and 5). The line 1 and 4 is the reason that the operator new(sizeof(Account),memory) can be used. Or to say it the other way around. The object a will be instantiated in the memory area memory. Accordingly, the same holds for the C array b.

Failed allocation

If the memory allocations fails new and new[] will raise a std::bad_alloc exception. But, that is often not the behaviour you want. Therefore, you can invoke placement new with a constant std::nothrow: char* c new(std::nothrow) char[10]. This call causes that you will get a nullptr in the error case.

New handler

In the case of a failed allocation you can use with std::set_new_handler your own handler. std::set_new_handler returns the older handler and needs a callable unit. This callable unit should take no argument and return nothing. You can get the currently used handler be invoking the function std::get_new_handler.

Your own handler allows you to implement special strategies for failed allocations:

  • request more memory
  • terminate the program with std::terminate
  • throw an exception of type std::bad_alloc

Memory deallocation

delete

A with new previously allocated memory will be deallocated with delete.

Circle* c= new Circle;
...
delete c;

 

The destructors of the object and the destructors of a base classes will automatically be called. If the destructor of the base class is virtual, you can destroy the object with a pointer or reference to the base class.

After the memory of the object is deallocated, the access to the object is undefined. You can point the pointer of the object to a different object.

delete[]

You have to use operator delete[] for the deallocation of a C array that was allocated with new[].

Circle* ca= new Circle[8];
...
delete[] ca;

 

By invoking delete[] all destructors of the objects will automatically be invoked.

The deallocation of a C array with delete is undefined behaviour.

Placement delete

According to placement new, you can implement placement delete. But it's special that the C++ runtime will not automatically call placement delete. Therefore, it's the programmer's duty.

A typically used strategy is it to invoke in the first step the destructor and in the second step placement delete.  The destructor deinitializes the object and placement new deallocates the memory.

char* memory= new char[sizeof(Account)];
Account* a= new(memory) Account;  // placement new
...
a->~Account();                    // destructor
operator delete(a,memory);        // placement delete

Of course, the according statements and strategies holds for the usage of placement delete for C arrays.

What's next?

The plan is crystal clear. In the next post I will dig deeper in the overloading of operator new and delete.

 

 

 

 

 

 

 

 

 

 

 

title page smalltitle page small Go to Leanpub/cpplibrary "What every professional C++ programmer should know about the C++ standard library".   Get your e-book. Support my blog.

 

 

Tags: memory

Comments   

0 #1 Shanel 2017-01-30 14:17
Hello.This article was extremely interesting, especially because I was looking for thoughts on this
matter last Tuesday.
Quote
0 #2 Chong 2017-02-02 18:57
I'm no longer certain where you're getting your information, but great topic.
I needs to spend some time finding out more or working out more.
Thanks for magnificent info I was in search of this information for my mission.
Quote
0 #3 Fredric 2017-02-19 10:40
Exactly what I was looking for, regards forr posting.
Quote
0 #4 bridal abayas 2017-02-22 04:08
Wow that wwas unusual. I just wrote an extremely long comment but after I clicked submit
my comment didn't show up. Grrrr... well I'm not writing alll that ovdr again. Anyways, juust wnted to
say wonderful blog!
Quote
0 #5 Elvia 2017-03-07 17:44
Heya i'm for the primary tikme here. I found this board and I find It
really useful & it helped me oout a lot. I am hoping to present
one thing again and hdlp others such as you helped me.
Quote
0 #6 Patsy 2017-03-18 17:49
As a Newbie, I am always searching online for articles that can benefit me.

Thank you
Quote
0 #7 Julieta 2017-05-15 17:58
I likewise think therefore, perfectly written post!
Quote
0 #8 Margot 2017-05-28 22:29
Simply desire to say your article is as amazing. The clarity in your post
is simply cool and i could assume you're an expert on this subject.
Well with your permission let me to grab your feed to keep up to date with forthcoming post.
Thanks a million and please carry on the rewarding work.
Quote
0 #9 Swapna 2017-05-31 19:46
Could you also explain what happens when malloc and other glibc memory allocation routines are used with C++. Mainly, what can go wrong with this: msgSz += sizeof(int) + len * entrySz;
msg = (MessageHdr *) malloc(msgSz * sizeof(char));
char* cP = (char *)(msg+sizeof(MessageHdr));
memcpy((char *)(cP), addr, sizeof(Address));
cP = (char *)(cP+sizeof(Address));
Quote

Add comment


My Newest E-Books

Latest comments

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 153

All 456535

Currently are 177 guests and no members online