Skip to main content

Dynamic Memory allocation in C++

Similar to C, C++ supports allocating memory at run time in the heap.

 In C we use malloc(), calloc() and realloc() for this operation. And the memory thus allocated, is released using free().

 In C++ dynamic memory allocation uses two operators instead of functions,
new and delete. Both these operators work on all basic data types as well as user defined classes and structures

new operator

new operator allocates memory to a variable and returns a pointer to it. new does not need number of bytes to be allocated, instead it needs data type of pointee.


 int *ptr = new int;

Here memory is allocated to an integer and its address is stored in ptr.  Value pointed by this pointer is not initialized.


To initialize the pointee we can use
the modified form

int *ptr = new int(10);

We have allocated memory for ptr and stored 10 in the location pointed by ptr.

If new operator fails, it throws a bad_alloc exception.

new[] operator

The second version of new  is new[]. This is used to allocate memory for multiple values. And the pointer once allocated can be accessed  using array syntax.

For example, to allocate memory for a block of 10 integers, you can use

int *ptr2 = new int[10];/*allocate memory to 10 integers. */

Let us look at some examples with new and new[]
int main()
{
 int *ptr;
 ptr = new int;
 cout<<"Enter a number";
 cin>>*ptr;
 cout<<"You just entered"<<*ptr;
 float * arr = new float[5];
 for(int i=0;i<5;i++)
 {
 cin>>arr[i];
 }
 delete ptr;
 delete [] arr;
}
 

The program above allocates  5 floats using new float[5]. You can observe that 5 floats allocated for arr are accessed using subscript operator([]).

delete operator

delete operator is used for releasing memory allocated using new.
delete ptr;
delete []ptr2;

delete with square brackets (delete []) is used to release memory allocated to multiple values. It is used to release memory allocated using new []
Any memory allocated using new operator should always be released using delete to avoid memory leaks.


Memory Leaks

Whenever you allocate memory using new operator, you should always release the memory using delete, after you have completed its usage. Because unlike other variables, dynamically created variables are not destroyed automatically when they go out of scope.

If memory is not released, at some point of time, the program will run out of memory. This is called memory leakage.

new and delete for objects


Memory can be allocated to classes and structures  too  using new and delete operators. new will allocate memory to an object, create the object and also call the constructor for the object.

delete will call the destructor and then destroy the object and release the memory.

Difference between malloc and new:

You can still use malloc() in C++. But malloc needs the user to specify the number of bytes to be allocated and malloc does not call constructor for objects.


Memory allocated using malloc can be released using free. But free does not call destructor for objects.


int *ptr = malloc(sizeof(int));
*ptr = 10;
free(ptr);

Memory allocated using new should be released using delete. And memory allocated using malloc should be released using free.

this pointer

You see a special pointer this in many methods of the class. What is it?

this is a pointer to the object which called this method. It is a pointer to the current object. Whenever we use a non-static member of a class in a method, there is an implicit this-> present.

class A
{
   int m;
public:
   void print();
   int getm();
};
void A::print()
{
    cout<<this->m;
}
int A::getm()
{
    return this->m;
}

Remember the discussion that a static method can not use this pointer.

Comments

Popular posts from this blog

Ten questions in C/C++

Let us see some questions in C and C++ Write printf statement in C to print - I got 98% in Maths Can you execute a function before main() in C? If yes, how is it done? Can you write a program to find if a number is even without using modulo operator? How do you define a data member which is common to all objects of a class in C++? Can we have a single constructor for a class, but still create objects from the class passing zero/one and two parameters? What problems might occur if a class has no default constructor? Is the following statement correct? fprintf(stdout,"Hello world");   Why do we use the following statement in C++ program? using namespace std;  Can you write a single statement to check if the number is a power of 2?  What does the following statement mean in C/C++?4 if(a) b++;    So we have 10 questions. How many of these can you answer?   Do you need more questions in C and C++?    You can find t...

It is a constant

In good old days, C programmers would use preprocessor directive to define constants. e.g. #define s 10 But we know now that, as compiler never gets to see these, preprocessor statements are error prone. Hence we have const s. A constant - defined with keyword const promises that this entity is never going to change. And if we accidentally modify a const, compiler throws an error. Let us look at an example. #include<iostream> using namespace std; int main () { int a = 10 ; const int b = 12 ; a ++ ; b = 18 ; } When we compile this program, compiler tells us that default.cpp: In function ‘int main()’: default.cpp:8:7: error: assignment of read-only variable ‘b’      b = 18; So it is catching the error that we are trying to modify a const. Whenever a local variable or parameter need not be modified, declare it as a const.  Yes, we can make even parameters as constant. We can make objects constant or even me...

Abstract class

 If we can not create any objects of a class, then it is called an abstract class. A class is made abstract by adding at least one pure virtual function to it. Pure virtual function A function is said to be a pure virtual function , if it has no definition but has only declaration. Pure virtual function is defined with the keyword virtual and followed by return type, function name and "=0". class Shape { public: virtual void printarea() =0 ; }; int main () { Shape obj1; //error } Here printarea() function of Shape class is a pure virtual function as it has no body. To make a function as pure virtual function, you should use =0 at the end of virtual function declaration Abstract class When a class has at least one pure virtual function, it is incomplete and no objects can be created from that class. Such a class is called an abstract class . In the earlier example class Shape is an abstract class, and objects can not be created from t...