pointers and dynamic memory management

Upload: ramandeepkaursaini

Post on 05-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/31/2019 Pointers and Dynamic Memory Management

    1/30

  • 7/31/2019 Pointers and Dynamic Memory Management

    2/30

    Pointers are one of the most important features of C++

    language. Pointers need very careful handling. There are many

    reasons for using pointers.

    A pointer allows a function or a program to access avariable outside the preview of function or program.

    Use of pointer increases makes the program execution

    faster.

    Using pointers, arrays and structures can be handled inmore efficient way.

    To communicate with operating system about memory.

  • 7/31/2019 Pointers and Dynamic Memory Management

    3/30

    UNDERSTANDING POINTERS

    Figure: Memory Organisation

    Each memory location is assigned a unique number called location

    number oraddress.

  • 7/31/2019 Pointers and Dynamic Memory Management

    4/30

    Amemory cellis either of one byte or more contagious bytes. Each

    cell can store one value at a given time. The address of a cell is alwaysthe address of first byte.

    Figure: Representation of a variable in Memory

  • 7/31/2019 Pointers and Dynamic Memory Management

    5/30

    Figure: Pointer as a variable

    Since pointer is a variable, its value is also stored in memory in

    another address. Suppose we assign the address of variable var

    to a variableptr.

  • 7/31/2019 Pointers and Dynamic Memory Management

    6/30

    The actual address of a variable is system dependent. During compilation and

    linking, addresses are assumed to be relative to some base address, usually 0.

    When the operating system loads the program in a free block, all the address

    are transformed with relative to address of the first memory location of the

    free block.

    Consider the following statement :

    ptr = &code;

    It will assign the number 1500 to the variableptr.

  • 7/31/2019 Pointers and Dynamic Memory Management

    7/30

    Syntax for declaring pointer variable is :

    type *ptr_name;

    Where type is a pre-defined or user-defined data types and indicates that

    the pointer will point to the variables of that specific data type, and

    character * indicates that variable is a pointer variable.

    For example the statement

    int *ptr1;

    Declares a pointer varieble ptr1 that can point to an integer type variable.

  • 7/31/2019 Pointers and Dynamic Memory Management

    8/30

    Once a pointer has been assigned the address of variable, the question remains

    as how to access the value of the variable using the pointer. This is done using

    indirection operator(*). Consider the following statements

    :

    int *ptrX, x = 10, y;

    ptrX = &x;

    y = *ptr X;

    cout

  • 7/31/2019 Pointers and Dynamic Memory Management

    9/30

    // Program to illustrate the use of address of

    // and indirection operators

    #include

    void main()

    {

    int *ptrX, x = 10, y;ptrX = &x;

    y = &ptrX;

    cout

  • 7/31/2019 Pointers and Dynamic Memory Management

    10/30

    A pointer is a variable that holds the address of another variable. We can

    have a variable that in turn holds an address of another variable. This type

    of variable will be known as pointer to pointer.

    A pointer to a pointer will be declared as:

    int **ptr;

    The value pointed to by a pointer to another pointer will be accessed as:

    **ptr;

  • 7/31/2019 Pointers and Dynamic Memory Management

    11/30

    // Program to illustrate the use of double indirection

    #include

    void main()

    {

    int a = 5, *ptrA, **ptrPtrA;

    ptrA = &a;

    cout

  • 7/31/2019 Pointers and Dynamic Memory Management

    12/30

    STATIC MEMORY ALLOCATION

    A situation where the amount of memory required is known before hand, and the

    compiler then can determine the memory requirements for the data as well as the

    instructions, in such a situation, memory allocation is known asstatic memory

    allocation.

    DYNAMIC MEMORY ALLOCATION

    When the amount of memory is not known before hand for a particular data item,

    then it is allocated at the execution time, i.e. when the program is running. In such

    a situation, memory allocation is known asdynamic memory allocation.

  • 7/31/2019 Pointers and Dynamic Memory Management

    13/30

    C++ language provides a set of operators

    calleddynamic memory management

    operators to allocate and de-allocate

    memory at execution time, i.e. dynamically.

    new operatordelete operator

  • 7/31/2019 Pointers and Dynamic Memory Management

    14/30

    The new operator allocates the memory and always returns a pointer to an

    appropriate type. The new operator is defined as:

    type * new type [ size in integer ] ;

    The following illustrates its use:

    int *intPtr;

    intPtr = new int [100];

    Allocates memory block of 200 bytes, 2 bytes for one integer value, total of

    100 integers.

    The new operator also permits the initialisation of memory locations during

    allocation. The syntax for doing so is:

    type *ptrVar = new type ( InitialValue);

  • 7/31/2019 Pointers and Dynamic Memory Management

    15/30

    The delete operator is a counterpart of new operator and it deallocates memory

    allocated by the new operator back to the free poll of memory.

    The syntax of delete operator is defined as:

    delete ptrVar;

    Where ptrVar can be a simple pointer variable or the name of the array of pointer to

    all types excepts class type.

    However, if ptrVar is an array of pointers to objects then we have to use the delete

    operator as shown below:delete ptrVar[]; or delete [] ptrVar;

    The second form is very handy if we want to deallocate more that one array with

    single use of delete operator.

  • 7/31/2019 Pointers and Dynamic Memory Management

    16/30

    We can use pointers for structure variables. Consider the following declarations:

    struct EMPLOYEE

    {

    int code;

    char name[20];

    int deptCode;

    float salary;

    };

    EMPLOYEE emp, *empPtr;

    These declarations create user-defined data type and give it name EMPLOYEE. Italso declares emp as variable of type employee and empPtr as pointer variable to type

    employee. Now the following statement

    ptr = &emp1;

    Can be used to assign the address of variable emp1 to pointer variable ptr.

  • 7/31/2019 Pointers and Dynamic Memory Management

    17/30

    You may expect that the elements can be accessed as shown below:

    *ptr.code *ptr.name *ptr.dept_code *ptr.salary

    But this approach will not work as the dot operator . has higher priority than

    the indirection operator *. The correct way is to write as:

    (*ptr).code (*ptr).name (*ptr).dept_code (*ptr).salary

    The syntax for accessing members of structures using arrow operator is:

    ptr->vname

  • 7/31/2019 Pointers and Dynamic Memory Management

    18/30

    #include

    using namespace std;

    class cl {

    int i;

    public:

    cl(int j) { i=j; }int get_i() { return i; }

    };

    int main()

    {

    cl ob(88), *p;

    p = &ob; // get address of obcout get_i(); // use -> to call get_i()

    return 0;

    }

  • 7/31/2019 Pointers and Dynamic Memory Management

    19/30

    Figure: Linear linked list of integer values with nodes

    typedef struct nodeType

    {

    int info;

    struct nodeType *next;

    } NODE;

    NODE *start;

  • 7/31/2019 Pointers and Dynamic Memory Management

    20/30

    Figure: Binary tree

    typedef struct nodeType

    {

    struct nodeType *left;

    int info;

    struct nodeType *right;

    } BNODE;

    BNODE *root;

  • 7/31/2019 Pointers and Dynamic Memory Management

    21/30

    Figure: Undirected graph Figure: Adjacency list for graph

    #define MAX 50

    typedef struct nodeType{

    int vertex;

    struct nodeType *link;

    } node;

    node *adj[MAX];

  • 7/31/2019 Pointers and Dynamic Memory Management

    22/30

    POINTER TO AN OBJECT

    When a pointer is initialized with the address of an object, then its

    members can be accessed using arrow -> operator.

    #include using namespace std;

    class cl {

    public:

    int i;

    cl(int j) { i=j; }

    };

    int main(){

    cl ob(1);

    int *p;

    p = &ob.i; // get address of ob.i

    cout

  • 7/31/2019 Pointers and Dynamic Memory Management

    23/30

    POINTER TO A MEMBER

    To obtain address of a member, the address of & operator is used along

    with fully qualified member name. A class member pointer is declared using

    the operator ::* , acombinatio of two characters without any space.

    Consider the following class:class Sample

    {

    private:

    int m;

    // . . .

    public:

    void show()

    // . . .};

    Pointer to data member m will be declared and initialized as:

    int Sample: :* intPtr = &Sample: :m ;

  • 7/31/2019 Pointers and Dynamic Memory Management

    24/30

    #include

    using namespace std;

    class cl {

    public:

    cl(int i) { val=i; }

    int val;

    int double_val() { return val+val; }

    };

    int main(){

    int cl::*data; // data member pointer

    int (cl::*func)(); // function member pointer

    cl ob1(1), ob2(2); // create objects

    data = &cl::val; // get offset of val

    func = &cl::double_val; // get offset of double_val()

    cout

  • 7/31/2019 Pointers and Dynamic Memory Management

    25/30

    All non-static member functions of an object have access to a special pointer

    named this. The this pointer holds the address of the object whose member

    function is invoked.//Program to demonstrate that this pointer is passed as

    //implicit first argument to a member function

    #include

    #includeclass Sample

    {

    private:

    int a;

    int b;

    public:

    void showAddress () {

    cout

  • 7/31/2019 Pointers and Dynamic Memory Management

    26/30

    Like structures, there are the classes where atleast one of the data members

    is a pointer to itself. These types of classes are useful for building complex

    data structures.

    class List

    {

    private :

    int data;

    List *next;

    public:// . . . Member functions

    };

  • 7/31/2019 Pointers and Dynamic Memory Management

    27/30

    PROBLEM OF DANGLING/WILD POINTERS

    The most common problem with pointers is that the programmerfails to initialize a pointer with a valid address. Such an initialized

    pointer, referred to as dangling/wild pointer, can end up pointing

    anywhere in memory that may include the program code itself or

    to the code of the operating system. When the system stopresponding, we say the system has hanged up and the only option

    left is to reboot the system. Therefore, care must be taken to

    initialize pointers with valid address.

  • 7/31/2019 Pointers and Dynamic Memory Management

    28/30

    PROBLEM OF NULL POINTER ASSIGNMENT

    One particular situation that happens is when the pointer points to address 0,

    which is called NULL. When it happens and no catastrophic situations had

    occurred, then the system will display a message Null pointer assignment on

    termination of the program.

    //Program to illustrate the cause of NULL pointer

    #include

    // global pointer variable , initialized to 0

    int *intPtr;

    void main()

    {

    *intPtr = 200; //write value on 0 address

    cout

  • 7/31/2019 Pointers and Dynamic Memory Management

    29/30

    PROBLEM OF MEMORY LEAK

    Another very serious problem with pointers is that of memory leak. Memory

    leak is a situation where the programmer fails to release the memory

    allocated at run time in module. Therefore, care must be taken to release the

    allocated memory block in a module where memory was allocated.

    // Program to illustrate the cause of memory leak#include

    void main()

    {

    . . . . .

    fun (); // invoke function named fun

    . . . . .

    }

    void fun()

    {

    int *intPtr;

    // allocate memory for n integer numbers

    intPtr = new [n*sizeof(int)];

    // work on the allocated block

    }

  • 7/31/2019 Pointers and Dynamic Memory Management

    30/30

    PROBLEM OF ALLOCATION FAILURES

    Allocation failure is a situation when the program through new operator request for a

    block of memory and the operating system could not fulfill the request of the program

    because the sufficient memory may not be available in the free pool of memory.

    Therefore, the programmer should take care of allocation failures and provide a safe

    exit in their programs on such failures.

    // Program to illustrate the allocation failure and

    // the way it should be handled

    #include

    void main()

    {

    int *intPtr;

    // allocate memory for n integer numbers

    intPtr = new [n*sizeof(int)];

    if ( intPtr == NULL )

    {

    cout