Yuliana
Yuliana

Reputation: 21

error in dynamic memory allocation from within a global variable

Here is description of my problem:

sizeof(Class_A) = 1076 bytes;

.

#include "Class_A.h"
Class_A_Wrapper{
  public:
     Class_A_Wrapper();                                            
     ~Class_A_Wrapper();  
  private:
     Class_A* class_a;                                    
};

Class_A_Wrapper::Class_A_Wrapper(){
  class_a = new Class_A();  
}

.

#include "Class_A_Wrapper.h"

Class_A_Wrapper a_wrapper;

Program crashes before the "main"-function call, at the moment, when it tries to create the "a_wrapper"-object, calls constructor for Class_A_Wrapper and finally calls "class_a = new Class_A()"; for reasons, which I don't understand, the compiler evaluates the sizeof(Class_A) as 1044 bytes, not 1076 as it should. This is not my code, this is not me, who declares objects globally in third files,but I need to find the reason for this crash and I am really puzzled. I would be very grateful for any comments and hints, thank you very much in advance.

Upvotes: 2

Views: 191

Answers (1)

anatolyg
anatolyg

Reputation: 28241

I had a similar problem once; it was caused by different compilation options for source file 2 and the one that defined Class_A constructor. In my case, the different options affected the size of enums (1 byte vs 4 bytes), so the new call allocated e.g. 1044 bytes but Class_A constructor initialized e.g. 1076 bytes.

There are other differences in compilation options that can matter (e.g. size of pointers, struct-packing options, maybe even some members of Class_A are declared using conditional compilation, i.e. #ifdef).

I am certainly not sure this is what happened in your case; just sharing my experience.

Upvotes: 1

Related Questions