Solved

ERROR IN SIZE OF CLASS

Posted on 2001-06-08
11
159 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
 
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
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

707 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now