Pointers and Dynamic memory in C++

 

Use Pointers in c

There are two ways that memory gets allocated for data storage:

  1. Compile Time (or static) Allocation
    • Memory for named variables is allocated by the compiler
    • Exact size and type of storage must be known at compile time
    • For standard array declarations, this is why the size has to be constant
  2. Dynamic Memory Allocation
    1. Memory allocated “on the fly” during run time
    2. dynamically allocated space usually placed in a program segment known as the heap or the free store
    3. Exact amount of space or number of items does not have to be known by the compiler in advance.
    4. For dynamic memory allocation, pointers are crucial.


Dynamic Pointers in c

Creating space using new :

Allocate space dynammically on the heap(free store) . new returns address of the allocated memory.Use pointers to reference the memory allocations on the heap.

new int;        // dynamically allocates an int 
 new double;     // dynamically allocates a double
new int[85];      // dynamically allocates an array of 40 ints 
 new double[size]; // dynamically allocates an array of size doubles
                   //  note that the size can be a variable define at first.
int * p;        // declare a pointer p 
 p = new int;    // dynamically allocate an int and load address into p 
// we can also do these in single line statements 
 int x = 12;
 int * list = new int[x];
 float * numbers = new float[x+52];
int * p = new int; // dynamic integer, pointed to by p

  *p = 10;      // assigns 10 to the dynamic integer
  cout << *p;     // prints 10

Another way to assigning :
list[5] = 12;          // bracket notation
  *(list + 7) = 52;         // pointer-offset notation
                    //   means same as numList[7]

delete :
To deallocate memory on the heap.
int * list = new int[40];  // dynamic array

  delete [] list;       // deallocates the array
  list = 0;             // reset list to null pointer

garbage :
created when we can no longer acccess previously allocated memory on the heap.

Dangling Pointer:
A pointer that no longer points to something valid on the heap.


resizing :

Create an entirely new array of the appropriate type and of the new size. (You'll need another pointer for this).
int * temp = new int[size + 5]; 

Change the pointer. You still want the array to be called "list" (its original name), so change the list pointer to the new address.
 list = temp; //you have changed the size of variable name list by pointing this to memory location which have size of
(size+5).

Hope you learnt something , stay tune for more examples and interesting facts about c++.
#keepCoding

Have something to add on Pointers and Dynamic memory  ? Please add in comments.

Follow us on Facebook, Google Plus and Twitter to get more Tech News and reviews.