This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: struct does not pad to alignment
Type: Stage:
Components: Library (Lib) Versions: Python 2.3
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: Nosy List: jepler, mattbehrens, tim.peters
Priority: normal Keywords:

Created on 2003-07-28 01:28 by mattbehrens, last changed 2022-04-10 16:10 by admin. This issue is now closed.

Messages (3)
msg17381 - (view) Author: Matt Behrens (mattbehrens) Date: 2003-07-28 01:28
Given this C code:

---
struct x {
        int a;
        char b;
};
 
int main() {
        printf("sizeof(x)=%d\n", sizeof(struct x));
}
---
 
And its Python counterpart:

---
import struct
 
print "calcsize(\"iB\")=%d" % struct.calcsize("iB")
---
 
On Intel (x86) Linux, Python 2.3b2+ (#2, Jul  5 2003,
11:28:28) [GCC 3.3.1 20030626 (Debian prerelease)] on
linux2, the former shows 8 while the latter 5.

I'm working with struct cdrom_tocentry from
linux/include.h, and if I use the results of
struct.pack, I get a string that's three bytes too
short.  Whether that is an actual issue or not depends
on whether Linux expects to be able to use the entire 8
bytes in an ioctl or not, I suppose.
msg17382 - (view) Author: Jeff Epler (jepler) Date: 2003-08-03 15:11
Logged In: YES 
user_id=2772

As a workaround you can manually pad, using "iBxxx" as the struct format string.
msg17383 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2003-08-03 16:37
Logged In: YES 
user_id=31435

You shouldn't pad the end "by hand".  The last paragraph of 
the struct module docs explains the intended method:

"""
Hint: to align the end of a structure to the alignment 
requirement of a particular type, end the format with the 
code for that type with a repeat count of zero. For example, 
the format 'llh0l' specifies two pad bytes at the end, assuming 
longs are aligned on 4-byte boundaries. This only works when 
native size and alignment are in effect; standard size and 
alignment does not enforce any alignment. 
"""

Python can't guess how a platform compiler is going to pad 
the *end* of a struct; indeed, it may well depend on C 
compiler options.  If the OP's compiler pads the end to int 
alignment in the examle, then the OP can tell the struct 
module that by using "iB0i".

I'm closing this now as WontFix, because Python is likely 
doing the best it can already here; and, if it's not, it can't be 
changed now without breaking working code (so if someone 
thinks they know how to do better, it would have to go in as 
a new function, or new option to calcsize (etc) -- then it's a 
new feature, not a bugfix).
History
Date User Action Args
2022-04-10 16:10:15adminsetgithub: 38943
2003-07-28 01:28:26mattbehrenscreate