vegadoom
vegadoom

Reputation: 471

sizeof returns different values for a struct when compiling different programs

I have 2 programs that share a header file. This header file defines a structure with a few members. There is then a #define: #define STRUCTURE_SIZE sizeof(OUR_STRUCTURE).

This structure is then used in shared memory with STRUCTURE_SIZE being used for the size argument to shmget().

Unfortunately, for the one program, STRUCTURE_SIZE ends up being 20758, while in the other one, it ends up being 20764. So when the second program tries to get the shared mem, shmget() returns EINVAL.

uname -a:

Linux machine 2.6.30.10-105.2.23.fc11.i686.PAE #1 SMP Thu Feb 11 07:05:37 UTC 2010 i686 i686 i386 GNU/Linux

g++ --version:

g++ (GCC) 4.4.1 20090725 (Red Hat 4.4.1-2)

Upvotes: 3

Views: 492

Answers (4)

Steve Townsend
Steve Townsend

Reputation: 54168

You might be able to gain some understanding by writing some code to check the offsets of field in OUR_STRUCTURE and print them out, using the two compilations in turn. Break down the total struct size to determine the size caused by each of its fields.

struct OUR_STRUCTURE
{
  double d;
  other_structure other;
  bool flag;
};

OUR_STRUCTURE ours;
cout << &ours.d - &ours << endl;
cout << &ours.other - &ours << endl;
cout << &ours.flag - &ours << endl;
cout << &ours + sizeof(OUR_STRUCTURE) - &ours.flag << endl;

Upvotes: 2

Luca Martini
Luca Martini

Reputation: 1474

Other possibilities:

  • The set of defines used in the two compilations differs, and the structure is defined conditionally on these defines
  • Some types can have different sizes in kernel and user space (this is rare, but it can happen)

Upvotes: 2

frast
frast

Reputation: 2740

The problem could be a packing or alignment issue. Find out how to tell your compiler how it should align structures.

Upvotes: 2

Paul R
Paul R

Reputation: 212979

A few possibilities:

  • you're compiling the two programs with different compilers and/or compiler switches
  • you have another header which appears before the header in question in one of the programs and this messes with #pragma pack or similar and doesn't restore the setting
  • a type that is used in the shared struct is defined differently in the two programs

(Note: the last two points can be applied recursively to any other structs which are used within the problem struct.)

Upvotes: 13

Related Questions