[Issue 24193] New: A size of unions with struct and bitfields is incompatible with C
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Mon Oct 23 03:01:15 UTC 2023
https://issues.dlang.org/show_bug.cgi?id=24193
Issue ID: 24193
Summary: A size of unions with struct and bitfields is
incompatible with C
Product: D
Version: D2
Hardware: x86_64
OS: Linux
Status: NEW
Severity: normal
Priority: P1
Component: dmd
Assignee: nobody at puremagic.com
Reporter: ttanjo at gmail.com
Here is a C code that declares a union with a struct and bitfields:
```c
#include <stdio.h>
typedef union {
struct {
int type:8;
int magic32;
} data;
int type:8;
} U;
int main(void)
{
printf("%ld\n", sizeof(U));
return 0;
}
```
```console
$ gcc --version
gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ gcc sample.c -o sample
$ ./sample
8
```
I expect that the size of the following equivalent D union `U` is same as the
result of C (i.e., 8).
```d
union U {
struct S {
int type:8;
int magic32;
}
S data;
int type:8;
}
pragma(msg, U.sizeof);
void main() {}
```
I checked the size with the following command:
```console
$ dmd --version
DMD64 D Compiler v2.105.2
Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved
written by Walter Bright
$ dmd -preview=bitfields sample.d
```
Expected result:
```console
$ dmd -preview=bitfields sample.d
8LU
```
Actual result:
```console
$ dmd -preview=bitfields sample.d
4LU
```
It causes problems when using C libraries in D including with importC.
Related: https://github.com/ldc-developers/ldc/issues/4477
--
More information about the Digitalmars-d-bugs
mailing list