Saturday 21 January 2017

Memory Management Operators

Share & Comment
 C uses malloc() and calloc() functions to allocate memory dynamically at run time. Similarly, it uses  the function free() to free dynamically allocated memory. We use dynamic allocation techniques  when it is not known in advance how much of memory space is needed. Although c++ supports these  functions, it also defines two unary operators new and delete that perform the task of allocating and  freeing the memory in a better and easier way. Since these operators manipulate memory on the free  store operators.
          An object can be created by using new, and destroyed by using delete, as and when required. A  data object created inside a block with new, will remain in existence until it is explicitly destroyed by  using delete. Thus, the lifetime of an object is directly under our control and is unrelated to the block  structure of the program. 
         
 The new can be used to create objects of any type. It takes the following general form:
 Pointer-variable    =    new data-type;
  

 Here, pointer-variable is a pointer of data-type. The new operator allocates sufficient memory to hold  a data object of a type data-type and returns the address of a object. The data-type may be any valid  type. The pointer-variable holds the address of the memory space allocated.
    
 Examples:
           P =   new int;
           q =    new float; 

 Where p is a pointer of type int and float. 
Tags:

Written by

Hy, i am a Code Geek ! And like to eduate others.

1 comments:

  1. I think this is good idea to set pointer to nullptr after delete that

    ReplyDelete

 
Copyright © C++ Programming | Designed by Templateism.com