ProgrammingHardProduct-company placement · C++
How many of these statements about C++ dynamic memory are correct? (i) Memory obtained with new[] must be released with delete[]. (ii) Applying delete to a null pointer does nothing. (iii) Memory obtained with malloc may be released with delete. (iv) Plain new reports allocation failure by throwing std::bad_alloc.
- A. 2
- B. 4
- C. 3
- D. 1
Correct answer: C. 3
(i), (ii) and (iv) are correct. (iii) is undefined behaviour: malloc pairs with free and new with delete; delete also runs a destructor that malloc never constructed.
More OOP with C++ and Java questions
- What happens when this is compiled? cpp struct K { const int c; int& r; K(int& x) { c = 1; r = x; } };
- Which line fails to compile? cpp struct A { A(int) { } }; struct B { B(A) { } }; void f(B) { } int main() { f(A(1)); // L1 f(1); // L2 }
- In C++, a destructor throws an exception while the stack is already being unwound because of another exception. What happens?
- What happens in C++11 or later? cpp struct T { ~T() { throw 1; } }; int main() { try { T t; } catch (int) { cout << "caught"; } }
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…
- What is printed? cpp struct G { G() { cout << "G"; } ~G() { cout << "g"; } }; G g1; int main() { cout << "M"; static G s; cout << "m"; }