1

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]
A
int *arr = new int *[10];
B
int **arr = new int *[10];
C
int *arr = new int [10];
D
Not Possible
new and delete    
Discuss it


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.
A
1 and 3
B
2 and 3
C
1 and 2
D
All 1, 2 and 3
new and delete    
Discuss it


Question 2 Explanation: 
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;
}
A
Compiler Error
B
5
C
Garbage Value
D
0
new and delete    
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; 
A
Compiler Error
B
Run-time Crash
C
No Effect
new and delete    
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;
}
A
Yes
B
No
new and delete    
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.
1

Company Wise Coding Practice    Topic Wise Coding Practice