Tech Study

C++ Memory Management: new and delete

C++ Memory Management

We know that arrays store contiguous and the same type of memory blocks, so memory is allocated to the array at the time of declaration. If we declare an array of size n, we can’t extend its size more than that during the runtime. If we declare an array of the maximum size, most of the memory can be wasted. 

C++ Memory Management allows us to allocate memory in run time and this feature is known as dynamic memory allocation. Unlike other languages like python, Java, etc C++ doesn’t take care of unused memory. Thus, we need to dynamically deallocate the memory manually after the completion of the lifetime of variables.

Allocation and Deallocation of memory are done using new and delete operators.

New operator

new operator is used to create a block of memory on the heap. 

Syntax:

pointer_variable = new datatype  

The above syntax is used to create an object using the new operator.

Here, 'pointer_variable' is the name of the pointer, 'new' is the operator, and 'data-type' is the type of the data.

Ex: int * q;

     q= new int;

    float * p=new char

Here q is a pointer pointing to the memory location containing an integer and p is a pointer pointing to the memory location containing a character.

We can also assign values to newly created objects.

Syntax:

pointer_variable = new datatype(value);  




Ex: int *p = new int(25);  

float *q = new float(0.9);  




We can also create an array using the new operator

Ex: int *arr = new int[10];

Delete operator

When memory is not required, we need to deallocate the memory and for this purpose, we use the delete operator.

Ex: delete p;

Java Final keyword

Introduction : java final keyword The final keyword present in Java programming language is generally used for restricting the user. …

Read more

If-else statement in java

Introduction: If-else statement in java Java if statement can generally used for checking the condition. It is supposed to check …

Read more