473,770 Members | 1,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Compiler specific?: struct with wrong sizeof

I have a TGA image header struct.
TGA has 18 bytes header, so the C struct too.

why this return 20?
sizeof(TGAHeade r)
I saw this in many structs. I believe compiler round up the size to 4
multiple.

Compiler is mingw gcc. Why this happens?
how can I pass the size in fread without hardcode the header size?
thanks
Jan 14 '07 #1
8 4247
Chameleon wrote:
I have a TGA image header struct.
TGA has 18 bytes header, so the C struct too.

why this return 20?
sizeof(TGAHeade r)
The compiler is free to insert padding to ensure correct alignment of
the struct members.
>
I saw this in many structs. I believe compiler round up the size to 4
multiple.
No. it's padding.
Compiler is mingw gcc. Why this happens?
how can I pass the size in fread without hardcode the header size?
You simply can't. Unless your platform has a means of packing
structures. Even it if does, the cost due to misaligned access may be
to high to justify their use.

--
Ian Collins.
Jan 14 '07 #2
Chameleon wrote:
>I have a TGA image header struct.
TGA has 18 bytes header, so the C struct too.

why this return 20?
sizeof(TGAHead er)
The compiler is free to insert padding to ensure correct alignment of
the struct members.
>I saw this in many structs. I believe compiler round up the size to 4
multiple.
No. it's padding.
>Compiler is mingw gcc. Why this happens?
how can I pass the size in fread without hardcode the header size?
You simply can't. Unless your platform has a means of packing
structures. Even it if does, the cost due to misaligned access may be
to high to justify their use.

Whow! How I miss this until now?!
I fread many structures in the past!
I am scaring to see my old code now!...
thanks!
Jan 14 '07 #3
Ian Collins wrote:
Chameleon wrote:
I have a TGA image header struct.
TGA has 18 bytes header, so the C struct too.

why this return 20?
sizeof(TGAHeade r)
The compiler is free to insert padding to ensure correct alignment of
the struct members.

I saw this in many structs. I believe compiler round up the size to 4
multiple.
No. it's padding.
Compiler is mingw gcc. Why this happens?
how can I pass the size in fread without hardcode the header size?
You simply can't. Unless your platform has a means of packing
structures. Even it if does, the cost due to misaligned access may be
to high to justify their use.
Properly packed structures can be crucial when reading data from binary
file headers, as the OP appears to be doing with the TGAHeader
structure.

Your compiler may have a "#pragma option" feature that you can use to
wrap your structure definition, to enforce the byte alignment you want.
You have to refer to your documentation for details.

For example, in Borland C++ Builder 6, I would use:

#include <iostream>

#pragma option push -a1 // set 1 byte alignment
struct test_data
{
char c;
int value;
};
#pragma option pop // restore original byte alignment

// Exactly the same structure, but using default alignment
struct test_data2
{
char c;
int value;
};

int main(int argc, char* argv[])
{
using namespace std;
cout << "Using 1-byte alignment:" << endl;
cout << "sizeof(test_da ta) == ";
cout << sizeof(test_dat a) << endl << endl;
cout << "Using default alignment:" << endl;
cout << "sizeof(test_da ta2) == ";
cout << sizeof(test_dat a2) << endl;
return 0;
}

On my computer, the output looks like this:

Using 1-byte alignment:
sizeof(test_dat a) == 5

Using default alignment:
sizeof(test_dat a2) == 8

You can see that with the #pragma in place, sizeof(test_dat a) is 5, as
you may expect from examining the contents of test_data.

In contrast, sizeof(test_dat a2) is 8, even though the structures have
identical contents. This is because the compiler pads the fields to
make them line up on 4-byte boundaries in this case.

Your results may be different, depending on which platform you are
using.

Regards,
Markus.

Jan 14 '07 #4
Chameleon wrote:
>I have a TGA image header struct.
TGA has 18 bytes header, so the C struct too.

why this return 20?
sizeof(TGAHead er)
The compiler is free to insert padding to ensure correct alignment of
the struct members.

What means "correct alignment of the struct members"?
Why this thing exists?
Jan 15 '07 #5
"Chameleon" <ch******@hotma il.comwrote in message
news:eo******** **@volcano1.grn et.gr...
>Chameleon wrote:
>>I have a TGA image header struct.
TGA has 18 bytes header, so the C struct too.

why this return 20?
sizeof(TGAHea der)
The compiler is free to insert padding to ensure correct alignment of
the struct members.


What means "correct alignment of the struct members"?
Why this thing exists?
It means that members of the struct are properly aligned by the compiler. A
32 bits int, for example, is usually aligned on a 4 byte boundary. This is
because on most architectures aligned reads/writes are faster than
misaligned reads/writes, and on some it is even mandatory (a misaligned
read/write can cause some kind of access violation).

Therefore a struct { char c; int i; }; is usually 8 bytes (depending on the
architecture really) because i is aligned on 4 bytes, causing 3 bytes
padding to be used between c and i. Note that struct { int i; char c; }; is
usually also 8 bytes on such an architecture - if you use the struct in an
array, the member 'i' of the second element needs to be 4-byte aligned as
well, so that's why in this case there's a 3 byte padding at the end of the
struct.

- Sylvester
Jan 15 '07 #6
Chameleon wrote:
>The compiler is free to insert padding to ensure correct alignment of
the struct members.
What means "correct alignment of the struct members"?
Whatever the compiler designers decided. In some cases, the processor has
alignment restrictions for 2 or 4 byte data types and is convenient that
the access to struct members can be done with one instruction. In others,
there are no absolute restriction but access to data aligned is faster, and
the intended users of the compiler want speed.

--
Salu2
Jan 15 '07 #7
Julián Albo a écrit :
Chameleon wrote:
>>The compiler is free to insert padding to ensure correct alignment of
the struct members.
What means "correct alignment of the struct members"?

Whatever the compiler designers decided. In some cases, the processor has
alignment restrictions for 2 or 4 byte data types and is convenient that
the access to struct members can be done with one instruction. In others,
there are no absolute restriction but access to data aligned is faster, and
the intended users of the compiler want speed.
And in other cases, it can yield corrupted reading i.e. if your
plateform doesn't feature a MMU.
Jan 15 '07 #8
Markus Svilans wrote:
Chameleon wrote:
Compiler is mingw gcc. Why this happens?

Your compiler may have a "#pragma option" feature that you can use to
wrap your structure definition, to enforce the byte alignment you want.
You have to refer to your documentation for details.
Also try: info gcc, C externtions, Type Attributes,

struct my_unpacked_str uct
{
char c;
int i;
};

struct __attribute__ ((__packed__)) my_packed_struc t
{
char c;
int i;
struct my_unpacked_str uct s;
};

Jan 15 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2235
by: Paul Sheer | last post by:
I have managed to build Python 2.3.3 with the aCC HP-UX C++ compiler by making a number of one-line changes. (For reasons beyond my control, I am forced to use this compiler and it has no C mode at all.) Typically to get the Python source code to compile under aCC one has to make a number of trivial changes of the form, struct whatzit *p; - p = malloc (sizeof (struct whatzit));
7
3349
by: Paul Sheer | last post by:
I need to automatically search and replace all fixed size buffer strcpy's with strncpy's (or better yet, strlcpy's) as a security and stability audit. The code base is large and it is not feasable to manually perform these changes. I would like perhaps a C++ parser that can automatically detect use of a strcpy to a buffer of fixed size. For instance, struct x { char member;
4
1523
by: Brian Stubblefield | last post by:
Dear group, I am a beginner to C. Below is a segment of a program that I am trying to debug: #include <stdio.h> #include <signal.h> /*#include <stdlib.h>*/ #define BIT char
12
2395
by: anars | last post by:
Hi, I have this struct initialized globally: struct riddle { char *text; .... } below, the function I call in main with the riddle struct as arg. is defined:
15
2034
by: David White | last post by:
The size of a struct can be affected by compiler packing. Suppose you need it to be a specific value for some reason (e.g., in firmware). How can you get the compiler to generate an error for the wrong size rather than assert it at run-time? Here is one way, but I don't know if it's guaranteed to work on any compiler: 1/(sizeof(struct my_struct) == correct_size); For me, the above produces a compile-time divide-by-zero error for the wrong...
29
2378
by: Ark | last post by:
A function int foo(struct T *x) { return (x+1)-x; } should always return a 1, no matter how T is defined. (And int could be replaced with ptrdiff_t for you pedants.) For one thing, it was amusing to watch how my compiler (the famed IAR EWARM for ARM) jumps through hoops to arrive at this answer.
43
3835
by: JohnQ | last post by:
Are a default constructor, destructor, copy constructor and assignment operator generated by the compiler for a struct if they are not explicitely defined? I think the answer is yes, because "there is no difference between a struct and a class except the public/private access specification" (and a few minor other things). When I create a class, I always start by declaring the default constructor, copy constructor and assignment operator...
159
7129
by: bernard | last post by:
howdy! please recommend a good c compiler. - should be small - should be fast - should come with a good ide - should be inexpensive i am using windows os.
4
2787
by: Sheldon | last post by:
Hi, I have a unique case where I need an array of structs that grows and within this array is another struct that grows in some cases. I'm having trouble allocating memory. Since I have never done this before, I'm sure it's a rookie mistake but I cannot seem to find it. Can someone render some assistance please? struct Fpos { grib_handle *h;
0
9453
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10254
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10099
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10036
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8929
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6710
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3607
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.