`sizeof` may give incorrect result in editor for structs containing bitfields
Bug type: Language Service
Describe the bug
- OS and Version: Ubuntu 20.04
- VS Code Version: 1.61.0
- C/C++ Extension Version: v1.7.0-insiders2
- Other extensions you installed (and if the issue persists after disabling them): N/A
- If using SSH remote, specify OS of remote machine: N/A
- A clear and concise description of what the bug is, including information about the workspace (i.e. is the workspace a single project or multiple projects, size of the project, etc).
Steps to reproduce
Code sample 1
#include <iostream>
struct test1 {
unsigned int a : 4;
unsigned int b : 4;
unsigned char c;
unsigned char d;
};
int main() {
std::cout << sizeof(test1) << std::endl;
}
Expected behavior
-
sizeof(test1)gives 4 when the program runs. (when memory alignment is set to 4 bytes) - However in the editor it shows 8.
Code sample 2
This time I add #pragma pack(1).
#include <iostream>
#pragma pack(1)
struct test1 {
unsigned int a : 4;
unsigned int b : 4;
unsigned char c;
unsigned char d;
};
int main() {
std::cout << sizeof(test1) << std::endl;
}
Expected behavior
-
sizeof(test1)gives 3 when the program runs. (when memory alignment is set to 1 byte) - However in the editor it shows 6.
Hi @ytx21cn . Thanks for reporting this. I'm able to reproduce the same issue in VS (where I can configure for Linux GCC, using Open Folder, a CppProperties.json file, and setting intelliSenseMode to linux-gcc-x64). I will open an issue against VS internally. (The IntelliSense implementation is shared between VS and the C/C++ extension for VS Code).
Hi @ytx21cn . Thanks for reporting this. I'm able to reproduce the same issue in VS (where I can configure for Linux GCC, using Open Folder, a
CppProperties.jsonfile, and setting intelliSenseMode tolinux-gcc-x64). I will open an issue against VS internally. (The IntelliSense implementation is shared between VS and the C/C++ extension for VS Code).
It doesn't look like it is a settings-dependent issue. When I place a single .cpp file to somewhere that any project would almost never live there (such as ~/Desktop), I observe the same result. Hence it is the fault of internal VS calculations that yield the wrong results.
I see this when the structure in question has internal padding. For example:
struct test {
unsigned short a;
unsigned short b;
unsigned short c;
unsigned int d;
unsigned int e;
};
With alignment 4 VScode v 1.77.3 shows the sizeof (struct test) to be 6, but at runtime it is 16. Arrays containing this structure are also shown incorrectly as a result.
This is internal bug 1418475.
It is not fixed as of VScode 1.93.1, C/C++ IntelliSense v1.22.7 (pre-release).
enum rx_desc_len {
RX_DESC_LEN_TYPE_1 = (sizeof(struct RxDesc)),
RX_DESC_LEN_TYPE_3 = (sizeof(struct RxDescV3)),
RX_DESC_LEN_TYPE_4 = (sizeof(struct RxDescV4))
};
All 3 sizes are wrong, the first two even come back as size 0.
{