+ 1

Malloc vs calloc | memory not initialized

Hi I have a sample program where I tried to verify that memory is initialized with calloc and not with malloc? Why output is 0 for both cases ? Should not malloc initialize value to 22? https://sololearn.com/compiler-playground/cbq89p8w5AtY/?ref=app

16th Dec 2024, 9:00 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 3
Evidently, it is merely casting the pointer types, not instantiating the objects. The statement a->display() works anyway because the display() method is available in memory regardless of whether the object is instantiated or not. Its address is resolved at compile time. The value of instance variable, a, is found at whatever offset from the pointer that it normally would be found, as though it were instantiated. Effectively you have created memory allocation for the objects but bypassed the constructor.
16th Dec 2024, 10:00 PM
Brian
Brian - avatar
0
Thanks Brian for details. I got the point now that new operator is the one which calls constructors , not the c related memory allocation functions. However, How to verify that malloc is less costlier compared to calloc as calloc has to initialize also. I thought I will have cout in constructor , but that does not get called at all.
17th Dec 2024, 6:06 AM
Ketan Lalcheta
Ketan Lalcheta - avatar