Below is a memory architecture used by C++ program:
datatype pointername = new datatype
int *new_op = new int; //Allocating block of memory int *new_op = new int;
If enough memory is not available in the heap it is indicated by throwing an exception of type std::bad_alloc and a pointer is return.
delete pointer variable
The object's extent or the object’s lifetime is the time of the object remains in the memory during the program execution. Memory allocation is slower than stack. In heap there is no particular order you can allocate memory as in stack.
Memory leak happens due to the mismanagement in memory allocations and deallocations. It happens in dynamic memory allocation. There is no automatic garbage collection in C++ as in Java. So programmer is responsible for deallocating the memory used by pointers.
Misuse of elevator in real life is an example of memory leak. Suppose you stay in an apartment which has 19 floors. You wanted to go to 10th floor and you pressed 10. The status of elevator is displaying as basement for 20 minutes. Then you release something is wrong, then you find out kids are playing in basement. They are continuously pressing basement button. Similarly once a pointer is done with its operations it should free the memory used by it. So that other variables can use the memory effectively.
By using delete keyword we can delete the memory allocated-Example:
*ex= new Example(); Delete ex;
But in the above example dangling pointer issue can happen.
A pointer pointing to a memory location of already deleted object is known as dangling pointer.
Dangling pointers arise due to object destruction, when an object reference is deleted or deallocated, without modifying the value of the pointer, so the pointer still points to the same memory location. This problem can be avoided by initializing the pointer to NULL.Example:
*ex = new Example(); Delete ex; ex = NULL;
Smart Pointer is used to manage the lifetimes of dynamically allocated objects. They ensure proper destruction of dynamically allocated objects. Smart pointers are defined in the memory header file.
Smart pointers are built-in pointers, we don't have to worry about deleting them, they are automatically deleted. They are used to manage the lifetimes of dynamically allocated objects. They ensure proper destruction of dynamically allocated objects. Smart pointers are defined in the memory header file.
S_ptr *ptr=new S_ptr(); Ptr->Action(); Delete ptr;