In: Computer Science
What function is used to deallocate dynamic memory when it is no longer required by your program? In your answer give the name of the function and its syntax, and how the C runtime system knows how much memory to deallocate. Give an appropriate example showing typical usage of this function.
delete() function is used to deallocate dynamic memory when it is no longer required by the program.
Let's consider an example:
Create a dynamic memory using new operator
int *n = new int[10];
Here, an array of size 10 is created in the heap memory which can only be accessed with the help of pointer.
To delete the data from heap memory, syntax is:
delete pointer-variable;
In our case it will be:
delete[] n;
C runtime system will know the amount of memory space being deallocated with the help of pointer which was pointing to that data, these pointers are stored in the main memory, remember that data in heap memory is dynamic in nature and cannot be accessed directly by main program, hence pointers are used to access such dynamic data from the heap.
Hope I answered the question
If you have any doubts or queries, feel free to ask.
And kindly upvote as an appreciation
Have a nice day.