What is new operator and delete operator?
Submitted by: Administratornew and delete operators are provided by C++ for runtime memory management. They are used for dynamic allocation and freeing of memory while a program is running.
The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new. The general form of using them is:
p_var = new type;
delete p_var;
new allocates memory on the heap. If there is insufficient memory, then new will fail and a bad_alloc exception will be generated. The program should handle this exception.
Consider following program:
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p;
try
{
p = new int; //dynamic allocation of memory
}
catch (bad_alloc x)
{
cout << “Memory allocation failed”;
return 1;
}
*p = 100;
cout <<”P has value”<<*p;
delete p; //free the dynamically allocated memory
return 0;
}
Submitted by: Administrator
The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new. The general form of using them is:
p_var = new type;
delete p_var;
new allocates memory on the heap. If there is insufficient memory, then new will fail and a bad_alloc exception will be generated. The program should handle this exception.
Consider following program:
#include <iostream>
#include <new>
using namespace std;
int main()
{
int *p;
try
{
p = new int; //dynamic allocation of memory
}
catch (bad_alloc x)
{
cout << “Memory allocation failed”;
return 1;
}
*p = 100;
cout <<”P has value”<<*p;
delete p; //free the dynamically allocated memory
return 0;
}
Submitted by: Administrator
Read Online C++ New And Delete Job Interview Questions And Answers
Top C++ New And Delete Questions
☺ | Explain realloc()? |
☺ | Explain the difference between realloc() and free()? |
☺ | What is new operator and delete operator? |
☺ | What is dynamic memory management for array? |
☺ | You can use C++ as a procedural, as well as an object-oriented language? |
Top C Plus Plus Language Categories
☺ | C++ Pointers & Functions Interview Questions. |
☺ | C++ Operator Overloading Interview Questions. |
☺ | C++ Exception Handling Interview Questions. |
☺ | C++ Virtual Functions Interview Questions. |
☺ | C++ Template Interview Questions. |