Memory Management Operator

Dynamic Memory Allocation in C++

Dynamic memory allocation is the allocation of memory storage for use in a computer program during the runtime of that program. It is a way of distributing ownership of limited memory resources among many pieces of data and code.

C Language uses malloc and calloc functions to allocate memory dynamically at run time. Similarly it uses the functions Free( ) to free dynamically allocated memory.

C++ also support those functions and 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.

The amount of memory allocated is determined by the program at the time of allocation and need not be known in advance. A dynamic allocation exists until it is explicitly released, either by the programmer or by a garbage collector implementation.

This is notably different from automatic and static memory allocation, which require advance knowledge of the required amount of memory and have a fixed duration. It is said that an object so allocated has dynamic lifetime.

Usually, memory is allocated from a large pool of unused memory area called the heap (also called the free store). For dynamic memory allocation we use the new and delete keywords, the old malloc and calloc from C functions are can now be avoided but are still accessible for compatibility and low level control reasons.

1. new operator

The new operator is an operator that expects the type of object to be created as an argument. new operator allocates sufficient memory to hold data of objects and it returns address of the allocated memory from the heap.

Syntax:

pointer-variable = new data-type;

Example:

int *p =new int;
float *q = new float;

*p=25;
*q=2.75;

Here, *p is a pointer variable of type int and *q is pointer variable of type float. *p is initializing int value 25 to newly created int object and *q is initializing float value 2.75 to float object. In another way:

int *p =new int(25);
float *q = new float(2.75);

new can be used to create a memory space for any data type including user defined data types such as arrays, structure and classes. new for one dimensional array is :

int *array=new int[10];

here, new creates memory space for an array of size 10. p[0] will refers to the first location, p[1] to the second and so on. using same way we can use for the class also.

A call to new for a class is not much different from a call for a fundamental type. Unless explicitly initialized, the default constructor is called for each new object, but you must make sure that a default constructor exists!

class ABC
{
--------
--------
};
int main()
{
ABC *ptr=new ABC;
}

This statement allocates memory for an object of the ABC class. If enough memory is available, the default constructor for ABC is executed and the address of a new object returned.

A program should make careful use of available memory and always release memory that is no longer needed. Failure to do so can impact the performance of your computer system. Memory that is released is available for further calls to new. Memory that has been allocated by a call to new can be released using the delete operator.

2. delete operator

The memory that your pointer points to because of the new operator can also be “deallocated,” not destroyed but rather, freed up from your pointer. The delete operator is used in front of a pointer and frees up the address in memory to which the pointer is pointing. If a data object is no longer needed, it is destroyed to release the memory space for reuse.

Any allocation of memory needs to be properly deallocated or a leak will occur and your program won’t run efficiently. Essentially, every time you use the new operator on something, you should use the delete operator to free that memory before exiting. The delete operator, however, not only can be used to delete a pointer allocated with the new operator, but can also be used to “delete” a null pointer, which prevents attempts to delete non-allocated memory.

Syntax:

delete pointer-variable;
delete [size] pointer-variable;

Example:

delete p; 
delete q;
delete []array;

Here, The memory pointed to by array, p and q variables have been freed up, which is a very good thing because when you’re manipulating multiple large arrays, you try to avoid losing the memory someplace by leaking it. If you do not call delete, the dynamically allocated memory space is not released until the program terminates. You can pass a NULL pointer to delete when you call the operator.

In this case nothing happens and delete just returns, so you do not need to check for NULL pointers when releasing memory. A delete expression is always a void type, so you cannot check whether memory has been successfully released or not.

Note: You must keep in mind that new T and new T() are not the equivalent. This will be more understandable after you are introduced to more complex types like classes, but keep in mind that when using new T() it will initialize the T memory location (“zero out”) before calling the constructor (if you have non-initialized members variables, they will be initialized by default).

Example:

#include<iostream>
using namespace std;
int main()
{
     int n,*p;
     cout<<"Enter array size:";
     cin>>n;
     p=new int[n];
     cout<<"Enter list of integers"<<endl;
     for(int i=0;i<n;i++)
          cin>>p[i];
     //logic for summation
     int s=0;
     for( int i=0;i<n;i++)
          s=s+p[i];
     cout<<"Sum of array elements is\n";
     cout<<s;
     delete [ ]p;
     return 0;
}
Output:
Enter array size:5
Enter list of integers
1 2 3 4 5
Sum of array elements is
15

Error Handling for new and delete

If you are working with an older compiler, please note that new returns a NULL pointer if not enough memory is available. The new handler is a function designed for central error handling. Thus, you do not need to design your own error handling routines each time you call new. Any exception that is not caught will terminate the program, however, you can install your own new handler.

A misuse of delete can be disastrous. do not call delete twice for the same object. do not use delete to release statically allocated memory.

The new and delete operators do not have to be used in conjunction with each other within the same function or block of code. It is proper and often advised to write functions that allocate memory and other functions that deallocate memory. Indeed, the currently favored style is to release resources in object’s destructors, using the so-called resource acquisition is initialization (RAII) idiom.

-wise man on earth

Related posts