new and delete operators
When we use new & delete operators in our program the heap memory (application memory) is being dynamically allocated. The allocated heap memory is used to store values and those memory is pointed by the pointers in the stack.
In pointers the new operator is dynamically allocates memory and assign a pointer variable to the start of that memory location.
In pointers the new operator is dynamically allocates memory and assign a pointer variable to the start of that memory location.
syntax: new datatype;
In the following example the new operator allocates memory dynamically and returns it address to the pointer variable pi. To access the stored values from the pointer location we use dereference(*) operator.
int *pi= new int; //pi=500
*pi=5; // storing value 5 in the pointer location 500
cout<< pi << *pi; //where pi=500 and *pi=5
*pi=5; // storing value 5 in the pointer location 500
cout<< pi << *pi; //where pi=500 and *pi=5
delete – used to deallocate dynamically.
delete pi;
What happens if the allocated memory is not released
- Garbage value in the heap.
Here once the pointer p is
allocated with a new value 10. So its address 700 is overwritten in this pointer
p. the value in the heap address 500 is
no longer referenced. So before reassigning new values to the pointer we have
to free up its value using delete keyword.
(e.g) delete p;
It only deletes the value from the heap which was pointed by the pointer p. It does not delete the pointer from the stack. It is unnecessarily points the location 500.
It only deletes the value from the heap which was pointed by the pointer p. It does not delete the pointer from the stack. It is unnecessarily points the location 500.
Solution to the dangling pointer
So, once the value is deleted. The pointer must be assigned with either 0 or NULL.
ii. Garbage collection
Whenever the heap memory is dynamically allocated in the program that should be freed up before the end of the program.
|
void x()
{
int *p=new int();
delete p;
p=NULL;
p=NULL;
}
Here before the function x() finishes the pointer p is freed up at the end of the function, So it's value popped out from the stack and the assigned heap memory 500 is no longer referenced.
Comments
Post a Comment