Static Memory Management, limitations, Dynamic Memory Management Mechanism, use of new and
delete operators, Methods for allocating and deallocating memory for single objects and array
of objects, use of set_new_handler function to slide-25specify our own handler
www.bookspar.com | Website for students | VTU NOTES
Memory for Program variables get allocated and
deallocated during the runtime only.
Eg – we write
int x;
in some function of the code. When the code containing this
line is compiled and linked, an executable file is generated.
When executable file is executed, all instructions contained inside
It, including ones to allocate memory for x are executed.
Hence memory gets allocated for ‘x’ during runtime.
This is known as Static Memory Allocation( although memory gets allocated during runtime only.)www.bookspar.com | Website for students |
VTU NOTES
The compiler writes instructions in the executable to
De-allocate the memory previously allocated for ‘x’ when it
encounters the end of the function in which ‘x’ was declared in the
source code.
When the executable file is executed, all instructions inside it
including the ones to deallocate memory for ‘x’ are executed.
Hence the memory for ‘x’ gets deallocated during runtime.
This is known as Static Memory Allocation
Static Allocation and deallocation of memory has limitations:
www.bookspar.com | Website for students | VTU NOTES
It is rigidThe programmers are forced to predict the total amount of
data the memory will utilize.They write statements to declare precalculated amounts of
MemoryDuring runtime, if more memory is required, static memory
allocation cant fulfill the need.
www.bookspar.com | Website for students | VTU NOTES
As in SM allocation and deallocation, in DM allocation and
deallocation also, memory gets allocated and deallocated during
Runtime.
However the decisions to do so is taken dynamically in
response to the requirements arising during runtime itself.
If the program is running and user indicates the need to feed in
more data, a memory block sufficient to hold additional amount of
data is immediately allocated.
For this code, using relevant functions and operators provided
by C & C++ has to be explicitly written in source code. www.bookspar.com | Website for students |
VTU NOTES
Again, once a certain block of memory is no longer
Needed, it can be returned to OS.
For this again, code using the relevant functions and
Operators provided by C & C++ has to be explicitly written
in the source code
www.bookspar.com | Website for students | VTU NOTES
//dynamic.cpp //new operator, keyword takes a
#include <iostream.h> // predefined datatype as operand( int)
void main() //new allocates memory to hold 1 value of
{ int *iptr; //datatype i.e. passed as a parameter to it in
iptr = new int;// heap( 4 bytes). Finally it returns the address
*iptr=10; //of the allocated block. The allocated block
cout << *iptr << endl; // can then be accessed through the
} //pointer
www.bookspar.com | Website for students | VTU NOTES
Statement: int *iptr;
1265
iptr
www.bookspar.com | Website for students | VTU NOTES
xxxx
Four bytes get allocated for iptr containing junk value with adrresses from 1265 to 1268(say)
Figure for Dynamic Memory Allocation
Statement: iptr = new int;
1265 5972
iptrThe new operator allocates memory in the heap to hold 1
integer type value. Suppose block from byte with address 5972 to byte with address 5975 get allocated. The new operator returns the base address of block (5972).This value gets stored in iptr.www.bookspar.com | Website for students |
VTU NOTES
5972 xxxx 4 bytes
www.bookspar.com | Website for students | VTU NOTES
Statement : *iptr=10;
1265 5972
iptr
fig - Dynamic Memory Allocation
iptr is dereferenced and value 10 gets written into the memory
Block of 4 bytes at which iptr points( 5972 to 5975).
105972
Statement : cout << *iptr << endl;
1265 5972
iptr
iptr is again dereferenced and value 10 gets written into the
memory block of 4 bytes to which iptr points
(5972 to 5975) is read. www.bookspar.com | Website for students |
VTU NOTES
5972 10
The new operator can be used to create multiple blocks of memory also shown in dynarray.cpp
www.bookspar.com | Website for students | VTU NOTES
The Set_new_handler() function –
New operator attempts to capture more chunks of
memory from heap during run-time.
If there is no memory available to satisfy this attempt,
we get out of memory condition.
new operator when faced with out-of-memory
condition, calls a global function -> new_handler
function, then throws an exception bad_alloc.
We can specify our own new handler() function also.www.bookspar.com | Website for students |
VTU NOTES
We can specify that the New operator upon
encountering out-of-memory-condition, calls a
function of our choice.
This is done by calling ‘set_new_handler() fn and
passing the name of function desired as a parameter
to it.
Prototype of set_new_handler is found in new.h
header file.
New_handler set_new_handler(new_handler);
New_handler is a datatype and a function pointer
Type.www.bookspar.com | Website for students |
VTU NOTES
The formal argument of the set_new_handler()
function is a function pointer.
If we pass name of our desired function as a
parameter to set_new_handler() function, all
subsequent out-of-memory conditions cause new
operator to call it and our desired function becomes
new_handler.
When set_new_handler() is called , it returns a
pointer to the previous new handler function
Illustrative example new_handler.cpp
Code for specifying a new_handler function
www.bookspar.com | Website for students | VTU NOTES
If os is unable to allocate the requested amount of memory, from given code, new operator fails. new_handler function is called.
The call to set_new_handler() before the call to new operator , has already set function myNewHandler as new handler.
Important Characteristic of new operator –
When its request for memory fails, it calls new
handler function repeatedly until the request is
satisfied.
We can make new_handler function log an error
message and then call the abort() function. www.bookspar.com | Website for students |
VTU NOTES
Void myNewHandler(){//statement to log a suitable error messageAbort();}
Another action – Replace the existing newhandler by another one i.e.
call the set_new_handler() from within the existing new handler and pass name of new handler as a parameter to it.
www.bookspar.com | Website for students | VTU NOTES
#include <new.h>
void main()
{ //make an attempt to resolve out of memory condition
If (above_attempt_fails)
set_new_handler(myAnotherNewhandler);
}Best way to define new handler is to allocate some buffer in advance and free it part by part when the
need arises. www.bookspar.com | Website for students | VTU NOTES
A constructor gets called automatically for each
object that has just got created.Appears as member function of each class whether
It is defined or not.Has same name as that of the class and doesn’t return anything (not even void )
Constructor Prototype
<class name> (<parameter list>);Constructor fulfills the need to guarantee the data initialization.
www.bookspar.com | Website for students | VTU NOTES
Domain constraints on the values of data
Members can also be implemented via
constructors.
Eg- We want value of all data member fInches of each object of class Distance to be between 0.0 and 12.0 at all times within the lifetime of object. But this condition get violated in case of an object just created. However introducing a suitable constructor to the class Distance can enforce this condition.
The compiler emdeds a call to the constructor for each object when it is created. Suppose a class A has been declared as follows.
www.bookspar.com | Website for students | VTU NOTES
/*A.h*/
Class A
{
Int x;
Public:
void setx(const int = 0);
int getx();
};www.bookspar.com | Website for students |
VTU NOTES
/*Amain.cpp*/
Void main()
{
A A1; //object declared … constructor called
}
Code for constructor getting called automatically for an object when it is created.
www.bookspar.com | Website for students | VTU NOTES
Statement in main() is transformed into
Following statements
A A1; //memory allocated for object (4 bytes)
A1.A //constructor called implicitly by compiler
Second statement is transformed to
A(&A1); -> C calls that object of class A passed as parameter for this pointer.
C++compiler after ensuring that none of nonmfs are accessing private data of the class A, it converts C++ code to C code.
www.bookspar.com | Website for students | VTU NOTES
A *Aptr;Aptr = new A; //
constrcutor called implicitly //by
compilerThe second statement is
converted into a sequence of 2 statements
Aptr = new A;Aptr -> A(); //
constructor called implicitly by compiler.
A(Aptr); //see chapter 2Constructors don’t allocate
memory for objects.They are mfs called for each
object immediately aftermemory has been allocated
for the object. www.bookspar.com | Website for students | VTU NOTES
class String
{ //character pointer to point at the
char *cStr; //character array
long unsigned int len; // to hold length of //character array
/*rest of the class string*/
};
www.bookspar.com | Website for students | VTU NOTES
www.bookspar.com | Website for students | VTU NOTES
101
3
a b c \0
101
cstr
len
s1 Fig- Memory layout of an object of class String
27
Constructors take arguments and canhence be overloaded by1. Passing initial values for the data members for the data members contained in the object of a particular class
www.bookspar.com | Website for students | VTU NOTES
Eg – The Distance class in a C++ program can
also be overloaded by passing initial values for data
Members iFeet & fInches as follows in class
Distance and member function definition. /*distance.h*/
class Distance
{
public:
Distance();
Distance(int, float); //prototype of parameterized
//constructor
/*rest of class Distance
}; www.bookspar.com | Website for students | VTU NOTES
/* beginning of distance.cpp*/
#include “Distance.h”
Distance::Distance(){
iFeet = 0;
fInches=0.0;
}
www.bookspar.com | Website for students | VTU NOTES
Distance :: Distance( int p, float q)
{
iFeet = p;
setInches(q);
}
/*definitions of the rest of the functiions of class
Distance*/
www.bookspar.com | Website for students | VTU NOTES
/*distTest1.cpp*/#include <iostream.h>#include “Distance.h”void main(){Distance d1(1, 1.1); //parameterized constructor //called
cout << “d1.getFeet() << “ “ << d1.getInches();}Listing shows A user defined parameterized
Constructor called by creating an object in theStack O/P – 1 1.1
SLIDE-Awww.bookspar.com | Website for students |
VTU NOTES
/*distTest2.cpp*/
#include <iostream.h>
#include “Distance.h”
void main()
{
Distance *dptr;
dptr = new Distance(1, 1.1); //parameterized constructor //called
cout << “dptr->getFeet() << “ “ << dptr->getInches();
}
Listing shows A user defined parameterized constructor –
called by creating an object in the heap.
O/P 1 1.1
SLIDE-B www.bookspar.com | Website for students | VTU NOTES
First line of main() in Slide-A and second line
Of main() in slide-B show the syntax for passing
values to the parameterized constructor
Parameterized constructor is prototyped and
defined like any other member function but it
doesn’t return any value.
www.bookspar.com | Website for students | VTU NOTES
Then the following statement will not compile
Distance d1; //Error no matching constructorThe formal arguments of the parameterized
constructor can be assigned default values asin other member functions. Here default constructor function should be provided, else an ambiguity error arise
www.bookspar.com | Website for students | VTU NOTES
The formal arguments of the parameterized
constructor can be assigned default values as
in other member functions.
Here default constructor function should be
provided, else an ambiguity error arise when we
attempt to create an object without passing any
values to the constructor
www.bookspar.com | Website for students | VTU NOTES
class Distance{public:
//Distance(); //zero argument constructor //commented out
Distance(int = 0, float=0.0); //default values
//given/*rest of the class Distance*/Listing – Default values given to parameters of a parameterized constructor make zero argument constructor unnecessary
www.bookspar.com | Website for students | VTU NOTES
If we write ,
Distance d1;
An ambiguity error arises if zero argument
constructor is also defined.
Reason – Both Parameterized and default
constructor can resolve this statement.
www.bookspar.com | Website for students | VTU NOTES
Lets create a parameterized constructor for theclass string and assign default value for theargument of the parameterized constructor.The constructor would handle the following
statements.String s1(“abc”);or
char *cPtr=“abc”String s1(cptr);
orchar Arr[10] = “abc”;String s1(cArr);
In each of these statements, we are passing thebase address of the memory block in which the
string itself is stored to the constructorwww.bookspar.com | Website for students |
VTU NOTES
www.bookspar.com | Website for students | VTU NOTES
p is a formal argument of the constructor.The address of the memory block containing thepassed string is 50. This address 50 is passed to the constructor. Hence value of p = 50.But constructor should execute in such a manner that adifferent block i.e. long to hold the string at which p ispointing should also be allocated dynamically in heaparea that extends from 101 to 104.The base address of this block of memory is stored
in pointer embedded in s1.The string is copied from the memory block at whichp points to memory block at which s1.cStr points.
Finally s.len is appropriately set to 3.www.bookspar.com | Website for students | VTU NOTES
www.bookspar.com | Website for students | VTU NOTES
50
Assigning a string to an object of class String
cStr
len
27
A b c \050
A b c \0 101
3s1
The value of cPtr is passed as a parameter to the
constructor. This value is stored in p. Hence p & cPtr
points to the same place.
s1.cStr should be made to point at a base address
of a different memory block of 4 bytes that has been
exclusively allocated for the purpose.
Only the contents of memory block whose base
address is passed to the constructor should be
copied into memory block at which s1.cStr points.
www.bookspar.com | Website for students | VTU NOTES
Assigning a string to an object of class String
A b c \050
A b c \0 101
3
50 cPtr
p
101
www.bookspar.com | Website for students | VTU NOTES
cStr
len
27
50
Fig - Assigning a string to an object of the class String
www.bookspar.com | Website for students | VTU NOTES
cStr
len
27
a b c \050
a b c \0 101
3s1
50
p
cArr
50
101
is very similar to II case. Here we are passing
the name of the array. But name of the array is
itself is a fixed pointer that contains the address
Of the memory block containing actual address of
array i.e. seen in diagram.
The formal argument of the constructor should be
as follows :
const char *const
1. It should be a constant pointer because throughout the execution of the constructor, it should continue to point to the same memory block. www.bookspar.com | Website for students |
VTU NOTES
2. It should be a pointer to a constant because
even inadvertently, the library programmer should
not dereference it to change the contents of the
memory block at which it is pointing.
3. Specify a default value for ‘p’(NULL) so that there
is no need to need to seperately define a zero default
Constructor
Definition of class String along with prototype of
the constructor and its definition are as follows
www.bookspar.com | Website for students | VTU NOTES
Class String
{
char *cStr;
long unsigned int len;
public: //Default constructor*/
String(const char *const p = NULL);
const char *getString();
/*rest of the class String*/
};
www.bookspar.com | Website for students | VTU NOTES
String::String(const char* const p){
if (p==NULL) { cStr=NULL; len = 0;}
else { len = strlen(p); // dynamically allocate a seperatecStr=new char[len+1]; //memory block & copy into itstrcpy(cStr,p); }
www.bookspar.com | Website for students | VTU NOTES
Const char *string::getString()
{
return cStr;
}
/*string.cpp*/
void main()
{
String s1(“abc”); //pass a string to parameterized
//constructor display the string
Cout << s1.getString() << endl;
} user-defined parameterized constructor
for acquiring memory outside the objectwww.bookspar.com | Website for students | VTU NOTES
Another function called getstring is written in class String that enables to display the string itself and returns a const char* so that only pointer to a constant can be equated to a call to this function
const char* p = s1.getstring();
www.bookspar.com | Website for students | VTU NOTES
It is called when object is created and equated to an existing object at the same time.
The copy constructor is called for an object being created.
The preexisting object is passed as parameter to it into the object for which it is called.
www.bookspar.com | Website for students | VTU NOTES
If we don’t define the copy constructor for the
class, the compiler defines it for us.
In either case, a call is embedded to it under 3
circumstances.
1. When an object is created an simultaneously equated to another existing object, the copy constructor is called for the object for object being created. The object to which this object was equated is passed as parameter to the constructor.
www.bookspar.com | Website for students | VTU NOTES
A A1 //default constructor calledA A2=A1; //copy constructor called Or A A2(A1); //copy constructor called
Or A *APtr = new A(A1) //copy constructor called Here copy constructor is called for A2 and forAPtr while A1is passed as parameter to the copyconstructor in both cases.
www.bookspar.com | Website for students | VTU NOTES
When an object is created as a nonreferenceformal argument of a function. The copyconstructor is called for the argument object.The object passed as parameter to the functionis passed as parameter to the constructor.void abc(A);A A1; //default constructor called abc(A1) // copy constructor calledVoid abc( A A2){/* definition of abc() Here again copy constructor is called for A2, while A1 is passed as a parameter to the constructor
}
www.bookspar.com | Website for students | VTU NOTES
A abc()
{ A A1; //default constructor called
//remaining part of definition of abc()
Return A1;
}
A A2 = abc(); //copy constructor called
Once more, copy constructor is called for A2 while A1 is passed as a parameter to the copy constrcutor
www.bookspar.com | Website for students | VTU NOTES
Class A
{
public:
A(A&); //default copy constructor
}
A::A(A& AObj) //default copy constructor
{ *this=AObj; //copies the passed object
//into the invoking object.
} www.bookspar.com | Website for students | VTU NOTES
Is converted as followsA A2; //memory allocated A::A(A& AObj) //default copy constructor
A2.A(A1) //copy constructor called for A2 and A1//is passed as parameter to it
This last statement is transformed toA(&A2,A1) //see this pointer in chapter2When above statement executes, ‘AObj’ (formal arg
in copy constructor becomes a reference to ‘A1’ whereas this pointer points at A2 the invoking object).
www.bookspar.com | Website for students | VTU NOTES
Suppose formal argument (AObj) of cc is not reference and following statement executes
A A2 = A1;
CC will be called for A2 and A1 will be passed
as parameter to it.
Reason – AObj is a nonreference formal arg
of constructor & an endless chain of calls to cc
will be initiated.
c.c->copy constructor www.bookspar.com | Website for students | VTU NOTES
However if formal arg of cc is a reference, no constructor will be called for it. This is because reference to an object is not a seperate object and no memory is allocated.
Hence a call to constructor is not embedded for it.
www.bookspar.com | Website for students | VTU NOTES
Recollect the conditions we decided to implement for all objects of class String.
Suppose an object of class String is created and at same time equated to another object of the class.
Eg – String(“abc”);String s2=s1;//cc is called for
s2 and //s1 passed as a parameter to it.
www.bookspar.com | Website for students | VTU NOTES
To overcome this problem of default cc , we define our own cc.
From within cc of a class String, a separate memory block must be allocated dynamically in heap. This memory must be equal in length to that of string at which pointer of object passed as parameter (s1) points. string.cpp
www.bookspar.com | Website for students | VTU NOTES
Class String
{
char *cStr;
long unsigned int len;
Public:
String(const String &); //rest of class String
};
www.bookspar.com | Website for students | VTU NOTES
String::String(const String& ss)
{ if(ss.cStr == NULL) //if passed object’s
{ //pointer is NULL
cStr = NULL;
len=0;
} else
{ len = strlen(ss.len);
cStr = new char[len+1];
strcpy(cStr, ss.cStr);
}
}www.bookspar.com | Website for students |
VTU NOTES
Void main()
{ String s1(“abc”);
String s2=s1;
cout << s1.getstring() << endl;
cout << s1.getstring() << endl;
}www.bookspar.com | Website for students |
VTU NOTES
Here in cc , formal arg is a constant that has to be a reference in order to prevent an endless chain of calls to itself. LP want to prevent change in value of object that get passed to the constructor
www.bookspar.com | Website for students | VTU NOTES
The prototype of a destructor
~<class Name>();
Need for Destructor – guarantees deinitialization of member data of a class and frees up the resources acquired by the object during lifetime.
Compiler embeds a call to destructor for every object when it is destroyed.
Void main() { A A1; } //A1 goes out of scope here
A1 goes out of scope before main() fn terminates.
www.bookspar.com | Website for students | VTU NOTES
Compiler embeds a call to destructor for A1. It embeds the following statement.
A1.~A(); //see chapter 2
An explicit call to destructor for an existing object is
forbidden. Above statement can be transformed into
~A(&A1); //see chapter2
Destructor will also be called for an object
that has been dynamically created in heap before the
delete operator is applied on the pointer pointing at it.www.bookspar.com | Website for students |
VTU NOTES
A *APtr;
APtr = new A; //Object created – constructor //called
…
…
delete APtr; //Object destroyed – destructor //called
Last statement is transformed into
APtr -> ~A(); //destructor called for //APtr
delete APtr; //memory for *APtr
//released.www.bookspar.com | Website for students |
VTU NOTES
1. Destructor is called for object i.e. going out of
Scope. Memory occupied by object itself is
deallocated.
2. Delete APtr;
Is transformed into
~A(APtr); //on this pointer
Destructor is a member function that is called for
each object just before the object goes out of scope
(gets destroyed)
1. Compiler embeds a call to destructor for each & every object i.e. going out of scope( gets destroyed)
www.bookspar.com | Website for students | VTU NOTES
Before After
Class A class A
{… {…
… public://implicitly by compiler
Public: ~A();//prototype inserted
//implicitly by compiler
…..
… …
//no destructor }; };www.bookspar.com | Website for students |
VTU NOTES
A::~A()
{
//empty function definition inserted implicitly by
//compiler
…
…
}
www.bookspar.com | Website for students | VTU NOTES
Lets add our own destructor to class A defined
In previous slide and verify whether destructor is
Actually called Implicitly by compiler or not.
//A.h
class A
{ int x;
public:
A();
void setx(const int =0);
int getx();
~A(); //our own destructor
}; www.bookspar.com | Website for students | VTU NOTES
/*A.cpp
#include “A.h”
A::A()
{
cout << “Constructor function of class A called\n”;
}
A::~A()
{
Cout << “Destructor function of class A called\n”;
}www.bookspar.com | Website for students |
VTU NOTES
#include <iostream.h>
void main()
{
A A1;
Cout << “End of Program”;
}
o/p – Constructor of class A called
End of program
Destructor of class A calledwww.bookspar.com | Website for students |
VTU NOTES
Eg – consider the following code block
{
…
String S1(“abc”);
…..
}
www.bookspar.com | Website for students | VTU NOTES
The memory allocated to S1 gets deallocated when this block finishes execution
But s1.cStr was pointing at a memory block that was dynamically allocated in the heap area.
After S1 gets destroyed, this memory block remains as locked up lost resource and s1.cStr is no longer available. This is memory Leak.
User defined destructor
String::~String() //our own destructor
{ if (cStr!=NULL) //if memory exists
delete [ ] cStr; //destroy it
} www.bookspar.com | Website for students | VTU NOTES
A::A()
{ cout << “Constructor of the class A called\n”;
}
A::~A()
{ //empty definition implicitly by compiler
}
Void main()
{
A A1;
Cout << “End of the Program\n”;
}www.bookspar.com | Website for students |
VTU NOTES
Class String is one such data type
Consider adding a function to class String
Void String :: addChar(char);
Function to add a character to a string
String S1(“abc”);
Pointer inside s1 points at a memory block of 4
Bytes. Executing s1.addchar(‘d’); would do
www.bookspar.com | Website for students | VTU NOTES
Another block of 5 bytes should get allocated.String contained in memory block at which s1.cStr is pointing should get copied into this new memory block.
Character d should get appended to stringNULL character should get further appended to the string
s1.str should be made to point to this new memory block.
The memory block at which s1.cStr was pointing previously should be deallocated to prevent memory leaks.
www.bookspar.com | Website for students | VTU NOTES
There are no memory leaks( destructor frees up unwanted memory)
There are no runtime errors( no 2 calls to destructor try to free up same block of memory)
Data is never in an invalid state and domain constraints on values of data members are never violated.
www.bookspar.com | Website for students | VTU NOTES
Top Related