1. Home
  2. Computer Science MCQs
  3. C++ and Object-Oriented Programming
  4. Which does new T provide that malloc(sizeof(T)) does not?

Added 30 Nov -0001

Which does new T provide that malloc(sizeof(T)) does not?

  1. It returns memory aligned to at least 4096 bytes, which malloc is not required to guarantee for any type
  2. It zero-initialises the object unless a constructor sets fields, which malloc never does for any type
  3. It can allocate arrays, whereas malloc cannot, because malloc knows nothing about element counts
  4. It runs T's constructor and reports failure by throwing std::bad_alloc instead of returning null Correct answer

Correct answer

D. It runs T's constructor and reports failure by throwing std::bad_alloc instead of returning null

13 views

MCQSEXAM

Explanation

Operator new separates allocation from construction: it obtains raw storage and then runs the constructor, while malloc only returns bytes. The throwing form raises std::bad_alloc on failure, and the nothrow form is the one returning nullptr. The matching delete runs the destructor before releasing memory, so mixing new with free, or malloc with delete, is undefined behaviour.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is D? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C++ and Object-Oriented Programming MCQs

Practise all C++ and Object-Oriented Programming MCQs

Similar MCQs