3

I ran an experiment on cpp.sh (no special flags) where the word size seems to be 4 bytes. In my experiment, I initialized two elements of type Data, a struct with just a single char, on the stack and printed out their addresses. I did the same with two variables of type char.

#include <iostream>
#include <bitset>

struct Data {
    char c;    
};

void PrintAddr(const void* ptr) {
    std::cout << std::bitset<32>((unsigned int) ptr) << std::endl;
}

int main()
{
    std::cout << "word size = " << sizeof(size_t) << std::endl;
    std::cout << "sizeof = " << sizeof(Data) << std::endl;
    std::cout << "alignof = " << alignof(Data) << std::endl;
    
    std::cout << "Data addresses: " << std::endl;

    Data a, b;
    PrintAddr(&a);
    PrintAddr(&b);
 
    std::cout << "char addresses: " << std::endl;
 
    char c, d;
    PrintAddr(&c);
    PrintAddr(&d);
}

Output:

word size = 4
sizeof = 1
alignof = 1
Data addresses: 
00000000010100000101001011101000
00000000010100000101001011100000
char addresses: 
00000000010100000101001011011111
00000000010100000101001011011110

It seems like padding is being added for variables a and b, of type Data, while there is none being added for type c and d. Why is this the case?

8
  • 1
    Please don't tag c when asking a question about C++. These are two distinct languages. Commented May 21, 2023 at 22:29
  • 3
    Just my 2p, but printing the addresses in binary makes this more confusing, not less. Commented May 21, 2023 at 22:33
  • 1
    Can reproduce with Clang (but not GCC), regardless of optimization level: godbolt.org/z/ex9Y3qPrq Commented May 21, 2023 at 22:35
  • 1
    This doesn’t adding the question, but none of the output in this program needs the extra stuff that std::endl does. ’\n’ ends a line. Commented May 21, 2023 at 22:36
  • 1
    Values of type object have alignment requirements that are implementation-defined. You don't have a reason for expecting the same alignment of a char and a struct.
    – user207421
    Commented May 22, 2023 at 2:13

1 Answer 1

5

A pedantic answer might be that the C++ language specification gives no guarantees of what the addresses of local variables might be. They might be next to each other, or there might be padding, or they might be completely unrelated! A language-lawyer might be happy to leave it at that.

If you're asking why a specific compiler does that, you could amend your question (or add tags) to specify that.

Note that these automatic variables probably wouldn't even have addresses until you actually take their address - they'd just live in registers. Probably more so for the char variables.

So that's my guess - the compiler you use is happy to pack automatic char variables on the stack (when you take their addresses), but is reluctant to pack automatic struct variables the same way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.