Skip to content

uctypes calculates incorrect structure size #17726

@jepler

Description

@jepler

Port, board and/or hardware

x86_64 coverage build

MicroPython version

MicroPython v1.26.0-preview.387.ge4e97f5aa7.dirty on 2025-07-20; linux [GCC 12.2.0] version

Reproduction

Use the code below:

>>> import uctypes
>>> si32 = {'v': uctypes.INT32}
>>> si16 = {'v': uctypes.INT16}
>>> si = {'v1': (0, si32), 'v2': (4, si32), 'v3': (8, si16), 'v4': (10, si16)}
>>> uctypes.sizeof(si)
16

and for comparison, this C program:

#include <inttypes.h>
#include <stdio.h>
#include <stddef.h>

typedef struct s16 { int16_t v; } s16;
typedef struct s32 { int32_t v; } s32;
typedef struct si { s32 v1, v2; s16 v3, v4; } si;
int main() {
    printf("sizeof(s16) = %zd\n", sizeof(s16));
    printf("sizeof(s32) = %zd\n", sizeof(s32));
    printf("offsetof(si, v2) = %zd\n", offsetof(si, v2));
    printf("offsetof(si, v3) = %zd\n", offsetof(si, v3));
    printf("offsetof(si, v4) = %zd\n", offsetof(si, v4));
    printf("sizeof(si) = %zd\n", sizeof(si));
}

which prints

sizeof(s16) = 2
sizeof(s32) = 4
offsetof(si, v2) = 4
offsetof(si, v3) = 8
offsetof(si, v4) = 10
sizeof(si) = 12

Expected behaviour

Expected the overall structure size to match C (12 bytes)

Observed behaviour

micropython reports the structure size as 16 bytes

Additional Information

I discovered this while working on m68k-micropython, where there's another problem with struct size calculation (m68k-micropython#15) -- There, 32-bit ints only have a 2-byte alignment requirement.

Code of Conduct

Yes, I agree

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy