Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

ERROR IN SIZE OF CLASS

Posted on 2001-06-08
11
162 Views
Last Modified: 2010-04-02
In the below class X :-
//////////////////////////////////////////
class X
{
   private:
           int i;
           short s;
           float f;
           

}

void main()
{
  X x; // object of the class X  

  cout<< sizeof(x);
  cout<< sizeof(int) << sizeof(short)<<sizeof(float);
 
}
/////////////////////////////////////////////////
my question is that the sizeof the object of the class
and the sum of the individual variable doesnt match
why it is so ? Use vc++ compiler for checking...


0
Comment
Question by:mansukhdakhara
11 Comments
 
LVL 30

Expert Comment

by:Axter
ID: 6170309
This is a double post.  Please delete your other duplicate question.
0
 
LVL 30

Expert Comment

by:Axter
ID: 6170311
>>? Use vc++ compiler for checking...
That's because of your project settings.

continue...
0
 
LVL 30

Expert Comment

by:Axter
ID: 6170315
Click on the Main menu "Project"
Then click "Settings"
Select the "C++" tab.
Change the catagory field to "Code Generation"
In the structure member field, that will state the byte settings for your structure.
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 30

Expert Comment

by:Axter
ID: 6170318
If you want your structure to show exactly the same size as it's members, you would have to set the above field to "1 Byte".

This could slow down your program, and make it less productive.
0
 
LVL 30

Accepted Solution

by:
Axter earned 100 total points
ID: 6170338
FYI,
This is not something that is unique to VC++.
Most compilers will compile to a minimum structor size, and most of them can be configured.
0
 
LVL 7

Expert Comment

by:KangaRoo
ID: 6170472
Modern day processors are happier if the data they fetch from memory is aligned to 4 or 8 byte boundaries, rather then on one byte. You class /might/ be represented internally as:

offset  size  member
00       4     i
04       2     s
06       2     Unused
08       4     f

adding up to 12 rather then 10 bytes. The compiler setting Axter decribes controls the alignment of classes and structures.
0
 
LVL 22

Expert Comment

by:nietod
ID: 6170714
>> In the structure member field, that will state the byte
>> settings for your structure.
This changes the default settings that will be applied to all strucutres and classes.  But you can also use the pack #pragma to alter the packing setting from the default, this allows you to pack different structures and classes to different degrees.  i.e.

#pragma pack(push)    // Save current packing setting.
#pragma pack(1)    // Swithc to byte alignment.
class X
{
private:
   int i;
   short s;
float f;
}                        
#pragma pack(pop) // Restore the previous packing setting.

also note that even if you switch to byte allighment, there will be cases where the structure/class size is not the sum of the member sizes.  For example, if a class/structure has virtual functions it may contiain data used to help impliment this.  if th clas/structure has a base class/structure, it will store this too and may store other information as well.  
0
 
LVL 4

Expert Comment

by:prashant_n_mhatre
ID: 6171127
KangaRoo has already mentioned this point. Let me elaborate.

Most CPUs require that objects and variables reside at particular offsets in the system's memory. For example, 32-bit processors require that a 4-byte integer reside at a memory address that is evenly divisible by four. This requirement is called "memory
alignment." On such architectures, a 4-byte int can be located at memory address 0x2000 or 0x2004, but not at 0x2001. On most UNIX systems, an attempt to use misaligned data results in a bus error, which terminates the program altogether. On Intel processors, the use of misaligned data is supported, but at a substantial performance
penalty. Therefore, most compilers automatically align data variables according to their type and the particular processor being used. This is why the size that structs and classes occupy may be larger than the sum of their members' size:

struct Employee
{
int ID;
char state[3]; /* CA, NY + null */
int salary;
};

Apparently, Employee should occupy 11 bytes (4+3+4). However, most compilers add an unused padding byte after the field "state" so that it aligns on a 4-byte boundary. Consequently, Employee occupies 12 bytes rather than 11. You can examine the actual size by using the expression sizeof(Employee).

0
 
LVL 22

Expert Comment

by:nietod
ID: 6171284
>> On most UNIX systems, an attempt to use
>> misaligned data results
It has nothing to do with the OS, its dictated by the architecture of the CPU and its memory unit.

>> On Intel processors, the use of misaligned data is supported, but
>> at a substantial performance penalty.
At most 2 clock cycles per access.  For a 1 clock cycle instrctuion, that is a 200% slower, on the other hand, its only 2 more clock cycles which is trivial.  In addition, the penalty is often avoided because the CPU prefetches data.
0
 
LVL 5

Expert Comment

by:BlackDiamond
ID: 6174037
I assume that you need to access the data without any offests included, hence this question.  Here is a quick workaround that will let you do that in this instance (I'll let use do the niceing of the class :->).  All of the data will be stored linearly in the unsigned character buffer "bytedata" which will be of the size that you specify.  If you need the memory to be accessed linearly, than use the pointer to that buffer.  If you want to reference by the type variables, then use the i, s, and f parameters (note that they are now pointers).  Hope this provides a little more insight...


class ByteData
{
   public:
      ByteData(size_t size) {
         bytedata = new unsigned char[size];
      }

      unsigned char * getByteData() {
         return bytedata;
      }
      void * getPtr (size_t offset) {
         return ((void *) (((unsigned long)bytedata) + offset));
      }
   private:
      unsigned char * bytedata;
};

class X
{
   public:
      X() {
         bytedata = new ByteData(sizeof(int) + sizeof(short) + sizeof (float));
         i = (int *)bytedata->getPtr(0);
         s = (short *)bytedata->getPtr(sizeof(int));
         f = (float *)bytedata->getPtr(sizeof(int) + sizeof(short));
      }
     

   private:
      ByteData * bytedata;
      int * i;
      short * s;
      float * f;
                   
};
0
 

Expert Comment

by:amp072397
ID: 6174879
I deleted the duplicate post. Anyone can report duplicate posts at http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt, even if it is not your question. Thanks!

amp
Community Support Moderator
Experts Exchange
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question