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.