I'm studying for a final exam and I stumbled upon a curious question that was part of the exam our teacher gave last year to some poor souls. The question goes something like this:
Is the following program correct, or not? If it is, write down what the program outputs. If it's not, write down why.
The program:
#include<iostream.h>
class cls
{ int x;
public: cls() { x=23; }
int get_x(){ return x; } };
int main()
{ cls *p1, *p2;
p1=new cls;
p2=(cls*)malloc(sizeof(cls));
int x=p1->get_x()+p2->get_x();
cout<<x;
return 0;
}
My first instinct was to answer with "the program is not correct, as new
should be used instead of malloc
". However, after compiling the program and seeing it output 23
I realize that that answer might not be correct.
The problem is that I was expecting p2->get_x()
to return some arbitrary number (whatever happened to be in that spot of the memory when malloc
was called). However, it returned 0. I'm not sure whether this is a coincidence or if class members are initialized with 0 when it is malloc
-ed.
p2->x
being 0 after malloc
) the default? Should I have expected this?#include <stdlib.h>
for malloc
:P)malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.
The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor. There are other differences: new is type-safe, malloc returns objects of type void* new throws an exception on error, malloc returns NULL and sets errno.
Explanation: All the statements about the new and malloc are correct. new is an operator whereas malloc() is a function. The constructor is called when new is used and new returns required type memory pointer.
It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program.
If the call fails, new will throw an exception whereas malloc will return NULL . For malloc , the caller has to specify the amount of memory to be allocated, while new automatically determines it.
No, p2->x can be anything after the call to malloc. It just happens to be 0 in your test environment.
What everyone has told you, new combines the call to get memory from the freestore with a call to the object's constructor. Malloc only does half of that.
Fixing it: While the sample program is wrong. It isn't always wrong to use "malloc" with classes. It is perfectly valid in a shared memory situation you just have to add an in-place call to new:
p2=(cls*)malloc(sizeof(cls));
new(p2) cls;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With