microsoft / vscode-cpptools

Official repository for the Microsoft C/C++ extension for VS Code.
Other
5.51k stars 1.55k forks source link

sizeof may give incorrect result in editor for structs containing bitfields #8251

Open ytxmobile98 opened 3 years ago

ytxmobile98 commented 3 years ago

Bug type: Language Service

Describe the bug

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

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

Colengms commented 3 years ago

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).

ytxmobile98 commented 3 years ago

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).

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.

nickstoughton commented 1 year ago

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.

sean-mcmanus commented 1 year ago

This is internal bug 1418475.

ewaldc commented 2 weeks ago

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. {VScode_issue