C++ new and delete
Question 1 |
How to create a dynamic array of pointers (to integers) of size 10 using new in C++?
Hint: We can create a non-dynamic array using int *arr[10]
int *arr = new int *[10]; | |
int **arr = new int *[10]; | |
int *arr = new int [10]; | |
Not Possible |
Discuss it
Question 1 Explanation:
Dynamic array of pointer having size 10 using new is created as,
int **arr = new int *[10];So, option (B) is correct.
Question 2 |
Which of the following is true about new when compared with malloc.
1) new is an operator, malloc is a function
2) new calls constructor, malloc doesn't
3) new returns appropriate pointer, malloc returns void * and pointer needs to typecast to appropriate type.
1 and 3 | |
2 and 3 | |
1 and 2 | |
All 1, 2 and 3 |
Discuss it
Question 2 Explanation:
See malloc() vs new
Question 3 |
Predict the output?
#include <iostream>
using namespace std;
class Test
{
int x;
Test() { x = 5;}
};
int main()
{
Test *t = new Test;
cout << t->x;
}Compiler Error | |
5 | |
Garbage Value | |
0 |
Discuss it
Question 3 Explanation:
There is compiler error: Test::Test() is private.
new makes call to the constructor. In class Test, constructor is private (note that default access is private in C++).
Question 4 |
What happens when delete is used for a NULL pointer?
int *ptr = NULL; delete ptr;
Compiler Error | |
Run-time Crash | |
No Effect |
Discuss it
Question 4 Explanation:
Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.
Question 5 |
Is it fine to call delete twice for a pointer?
#include<iostream>
using namespace std;
int main()
{
int *ptr = new int;
delete ptr;
delete ptr;
return 0;
}Yes | |
No |
Discuss it
Question 5 Explanation:
It is undefined behavior to call delete twice on a pointer.
Anything can happen, the program may crash or produce nothing.
There are 5 questions to complete.


