In C name 3 different ways memory leaks can occur And what a

In C++ name 3 different ways memory leaks can occur? And what are good practices
In C++ name 3 different ways memory leaks can occur? And what are good practices

Solution

1)Memory leak is occurred when we allocate memory using new operator which invokes parameter constructor or default constructor and initialise object.But then we dont deallocate it,

eg.

Ball * b =new Ball();

If we write above then it will cause memory leak as memory is not freed.

Best Practise:

Ball * b =new Ball();

;

;

delete b

Hence,Best practise is always deallocate memory using delete.

2)Suppose,When we create pointer of base class and point to object of derived class which is legal.But while calling destructor we just call delete baseptr then it will cause memory leak as it will call only base class destructor no derived class destructor will be called.

e.g.

Base *ptr=new Derived()

delete ptr

Above will cause memory leak

Best Practise:

Above scenario can be handled by declaring virtual destructor ,so it will call derived class destructor also.

3)Dangling pointer will cause memory leak.It condition when pointer points invalid memory location.

Suppose,

int* a=new int()

int* b=new int()

b=a

delete a

hence here b will be dangling pointer

4)Default copy constructor will not give proper result when class has pointer as member variable then it will just does shallow copy i.e. only references will get copied no new objects are formed.So,when we change pointer varible of one class object it will also change the others value.So,this is memory leak

Best Practise:To avoid this we need to create our copy constructor which will allocate memory to pinter separatly.

In C++ name 3 different ways memory leaks can occur? And what are good practices In C++ name 3 different ways memory leaks can occur? And what are good practice

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site