What happens to class members when malloc is used instead of new?

Posted by Felix on Stack Overflow See other posts from Stack Overflow or by Felix
Published on 2010-05-26T15:11:16Z Indexed on 2010/05/26 15:21 UTC
Read the original article Hit count: 234

Filed under:
|
|

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.

  • Is this behavior (p2->x being 0 after malloc) the default? Should I have expected this?
  • What would your answer to my teacher's question be? (besides forgetting to #include <stdlib.h> for malloc :P)

© Stack Overflow or respective owner

Related posts about c++

Related posts about memory-allocation