IBM Interview Question
Software Engineer / Developersi guess there is one more issue with using malloc...it doesnot take care of alignment issues, I mean that if you do malloc(40) for 10 integers, it doesnot guarantee 4-byte alignment..PLZ COMMENT if I am wrong
I guess if you use specific type of pointer to cast it, it would be fine, like (int *) pr = malloc( .. )
true, malloc will allocate the space you have requested. the question mentions c++. please note that malloc returns a void pointer. in c++ you cannot type cast a void pointer unlike c. hence we use new operator in c++ because new returns the pointer corresponding to the class being instantiated.
the primary issue is the call to the constructor. there is no problem with the casting as mentioned above. infact, even if some compilers refuse to cast 'c-style', you could use a static_cast or a reinterpret_cast to achieve this. as long as the size given to malloc is right you will get a proper object (uninit ofcourse)
The difference between "new" and "malloc" is that, if you use new, you are not only allocate the memory for the object, but also call the constructor for the object.
- jianwei.sun September 13, 2008For example
Class Simple
{
public:
Simple()
{//constructor code.
}
}
If you "new" the class, the constructor code will be called, if you use malloc, only memory for the class will be allocated, no constructor code will be called.