C++ Dynamic Memory

October 09, 2015 Posted by WithU Technologies

Code (Text) Memory: It stores the instructions, which need to be executed.

Global Memory: They are accessible anywhere during the whole lifecycle of the application as long as the application is running.

Stack memory: It is the predefined memory used by the datatype and local variables along them to store values. It also stores the information of function calls.

Heap memory: Unused memory for the program which only to be used when the program runs.
-          Application’s heap is not fixed.

-          There is no set rule for allocation and De-allocation of the memory.

-          Programmer control the heap memory as it is known as the Free pool of memory.

-          It is also known as dynamic memory and using the heap I known as dynamic memory allocation.

·         Certain times we don’t know the memory is to be used to store a particular information.

·         And the size of the undefined memory can only be determined during run-time.

For those situations we use new operator for the variable of a given type to allocate the free heap memory during run-time.

Example:

new int; //allocates memory size required for storing an integer in the heap memory

Dynamic allocation of memory

Now we need to assign a value to that heap memory with help of pointer.

int main() {

      new int;

      int *poin=new int;

      *poin = 36;

}

·         We initialize a pointer variable named poin with the int data type and then assign it to dynamically allocated memory (heap).

·         The pointer is stored in the stack as local variable, and holds the heap’s allocated address as its value.

·         The value of 36 is stored at that address which is dynamically allocated to operate during run-time i.e the new integer.

·         Stack memory automatically manage the space use for local variables with the help of lookup table.

·         But incise of heap memory, it needs to be managed manually by the programmer.

·         So, it would be a better practice to delete a dynamic memory allocation after operation to free up some space using the delete operator.

#include <iostream>
using namespace std;

int main() {

      new int;

      int *poin=new int;

      *poin = 5;

      cout<<*poin<<endl; //Outputs 5

      delete poin;  //deletes the dynamically allocate memory only

      *poin = NULL;

      cout<<*poin; // Now it outputs 0, as it was assigned as a NULL pointer

}

Delete operator only deletes the dynamically allocated memory. The pointer remains as it is in the stack memory.

And it would be better to assign a NULL after those dangling pointers which are no longer assigned with any address.

Even we can also store arrays dynamically into the heap memory.

int main() {

      new int;

      int *poin=new int[15]; //Request memory for an array to store 15 elements

      delete []poin; // Use to delete the heap memory assigned for array

}