Which does new T provide that malloc(sizeof(T)) does not?
Correct answer
D. It runs T's constructor and reports failure by throwing std::bad_alloc instead of returning null
13 views
D. It runs T's constructor and reports failure by throwing std::bad_alloc instead of returning null
13 views
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.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.