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

SameerRathoud 4,727 views 24 slides Feb 20, 2014
Slide 1
Slide 1 of 24
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24

About This Presentation

This presentation will help reader in understanding some basic concept of dynamic memory management in C++.


Slide Content

Memory Management in C++
Peeling operator new() and delete()
Sameer Singh Rathoud

About presentation
Thispresentationwillhelpreaderinunderstandingsomebasicconceptofdynamic
memorymanagementinC++.

operator new() and delete()
operator“new()”and“delete()”arethebuilt-inlanguagesupportfor
dynamicallyallocationandde-allocationofmemoryInC++.

About operator new()
•Operator“new()”canbeuserdefinedorbuilt-in.
•Ifaprogrammerdon’tspecifyoperator“new()”,built-inoperator
“new()”willbeusedbydefault.
•Operator“new()”canbedefinedgloballyorasamemberofclass.
•Thereshouldbeonlyoneglobaloperator“new()”withparticulartypesof
parameterinanexecutable.
•Operator“new()”global/localonlyallocatesthememoryfromheap.
•Memoryallocatedonheapishavinglifespanbeyonditsoriginalscope.
Sotopreventthememoryfromleaking,programmerexplicitlyneedto
releasethememory

Advantages of new()
Programmerdon’tneedtodefinethesizeof(“sizeof”)memorytoallocatewhile
usingoperator“new()”.
Provideflexibilitytotheprogrammertooverloadtheoperator“new()”asper
need.
•Improvescodereadability.
•Noneedofcastingexplicitly.
•Returnsnullpointeronfailureandprovideflexibilitytotheusertohandlethe
scenario.

Minimal definition of operator new()
Thisistheminimaldefinitionofoperator
“new()”takingtheargumentassizeof
memorytobeallocatedandreturningthe
void*ofthememoryallocatedby“malloc”.
extern"C"void*malloc(size_t);
void*operatornew(size_tsz){
returnmalloc(sz);
}
classA{
};
intmain(){
A*a=newA();
return0;
}

Handling new() failure
AProgrammercanhandlefailureof
operator“new()”intwoways:
•Programmercanuse“nothrow”
optionandcheckforthenull
pointer.
•Programmercanuse“try–
catch” block to catch
“std::bad_allocexception”.
Method 1:
A *p_a = new(nothrow) A();
If(!p_a)
{
// new() failure handling
}
Method2:
try{
A*p_a=newA();
}
catch(std::bad_alloc&ex){
//new()failurehandling
}

Handling new() failure -_new_handler and set_new_handler
•Ifoperator“new()”failstofindmemoryitcallspointertoafunction
“_new_handler()”.
•If“_new_handler()”againfailstofindmemoryitthrows“std::bad_alloc
exception”.
•Aprogrammercansethisown“_new_handler” usingfunction
“set_new_handler()”.

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++
Aprogrammercanuse“malloc()”and“free()”routineswithC++
Caution:
•Nevermix“new()”with“free()”or“malloc()”with“delete()”.
•Alwaysremember“malloc()”and“free()”donotcallconstructorand
destructor.Sobecarefultousetheseroutineswithclassobjects.
C++doesn’tsupport“realloc()”likeoperator.

Allocation and de-allocation of array
•Operator“new()”and“delete()”canalsobeusedforallocatingandde-
allocatingofmemoryforarrayofobjects.
•Whencallingtheoperator“delete()”forthepointertoanarray,a
programmerhastouse[]with“delete()”tofreeentirearray’smemory.
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
Constructionofanobjecthappensin3steps:
•Allocatethesufficientmemorytoholdtheobject.
•Ifallocationissuccessfulcalltheconstructorandcreateanobjectinthat
memory.
•Storetheaddressoftheallocatedmemoryinthespecifiedpointer.
A *p_a = new A();
•AllocatethesufficientmemorytoholdtheobjectofclassA.
•IfallocationissuccessfulcallA()andcreateanobjectofAinthatmemory.
•Storetheaddressoftheallocatedmemoryinp_a.

Construction and destruction continue …
Destructionofanobjecthappensin2steps:
•CallthedestructorofA(~A())
•De-allocatethememorypointedbyp_a;
delete p_a;

Construction and destruction continue …
•Allocationandde-allocationofmemoryishandledbyoperator“new()”
and“delete()”.
•Constructionanddestructionofanobjectishandledbyconstructor
anddestructor.
•Beforeinvocationofconstructormemoryhasbeenalreadyallocated
fortheobject,sothatconstructorcandoitswork.
•Destructoronlydestructstheobjectandnotresponsibleforcleaning
upthememoryandafterdestructorcompletesitsjobthenonly
memorywillgetcleanedup.

Object placement syntax
•Asdefaultoperator“new()”allocatesthememoryfromthepooloffree
memory(heap).
Alwaysthismightnotbetherequirement.Maybeuserwantedtocreateanobject
atanyspecificlocation(e.g.incaseofsharedmemory).
•AsthesolutionofthisC++providesdefaultplacementversionofoperator
“new()”,tocreateanobjectatspecifiedlocation.
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.
Aswehaveconstructedanobjectinthememoryalreadygotallocated,weneeda
waytodestroytheobjectwithoutreleasingthememory.
p_a->(~A());
shm_free(p_a);

Object placement syntax continue …
Placementsyntaxcanalsobeusedtopassadditionalparameters.
Placementsyntaxcanbeusedtoresizetheallocatedmemory,butcanonlybe
usedforbuilt-intypes,becauseofobjectconstructionanddestructionissues
andhighlynotrecommended.

Class specific operator new() and delete()
Aprogrammercanspecifyaclassspecificoperator“new()”and“delete()”.
class A {
public:
void* operator new(size_t);
void operator delete(void*);
};
Now“A::operatornew()”willbeused
insteadofglobaloperator“new()”.The
specifiedversionofoperator“new()”willonly
beworkforclassAandclassesderivedfromA.
Itwon’tbeusedforarrayofobjects,aswe
havenotspecifiedthearrayversionofoperator
“new()”.
void* operator new[](size_t);

Overloading operator new() and delete()
•Aprogrammercanspecifyanynumberofoverloadedoperator“new()”with
differentsignature.
•Itisnotpossibletooverloadoperator“delete()”withdifferentsignature.
•Classspecificoverloadedoperator“new()”and“delete()”obeysthesame
scoperuleasothermemberfunctionsofclass.
•Andclassspecificoperator“new()”and“delete()”willhidetheglobal
operator“new()”and“delete()”,whichmaygiveerrorincaseofincorrect
usage(likenooperator“new()”foundforclasswithspecifiedsignature).
class A {
public:
void* operator new(size_t, int);
};
A* p_a = new() A; // will get error

Overloading operator new() and delete() continue …
Aprogrammercansolvethusprobleminfewways.
•Defineaclassspecificdefaultoperator“new()”.
•Canexplicitlygivecalltoglobaloperator
“new()”.
•Cangivethedefaultvaluetotheargument.
Method 1:
class A {
public:
void* operator new(size_t,
int);
void* operator new(size_t);
};
A* p_a = new() A;
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*operatornew(std::size_t)throw(std::bad_alloc);
•void*operatornew[](std::size_t)throw(std::bad_alloc);
•voidoperatordelete(void*)throw();
•voidoperatordelete[](void*)throw();
•void*operatornew(std::size_t,conststd::nothrow_t&)throw();
•void*operatornew[](std::size_t,conststd::nothrow_t&)throw();
•voidoperatordelete(void*,conststd::nothrow_t&)throw();
•voidoperatordelete[](void*,conststd::nothrow_t&)throw();

Variants of built-in operator new() and delete() continue …
•inlinevoid*operatornew(std::size_t,void*__p)throw(){return__p;}
•inlinevoid*operatornew[](std::size_t,void*__p)throw(){return__p;}
•inlinevoidoperatordelete(void*,void*)throw(){}
•inlinevoidoperatordelete[](void*,void*)throw(){}

End of Presentation . . .