简体   繁体   中英

Zero length struct: what's the pointer pointing at?

I've been playing around with C and came across this case.

There's two zero width structs, C and D where D contains C .

As we can see, the pointer to the zero length struct b has an address that is one byte offset from the also zero length struct a (see output below).

In this case, what do the &a and &b addresses point to?

Why is there one byte offset between them?

Shouldn't they both be null pointers?

#include <stdio.h>

struct C {};

struct D {
    struct C wreck;
};

int main () {

    struct C a;
    struct D b;

    printf("struct C a size %lu stored at %p\n", sizeof(a), &a);
    printf("struct D b size %lu stored at %p\n", sizeof(b), &b);

    return 0;
}

Sample output:

$ ./struc 
struct C a size 0 stored at 0x7ffe05c8b6e6
struct D b size 0 stored at 0x7ffe05c8b6e7

Compiler used:

$ gcc --version
gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0

what do the &a and &b addresses point to?

&a is the address of a struct of type C , and &b is the address of a struct of type D . It is the same as if the structures were of non-zero size. Why would it be any different?

Why is there one byte offset between them?

Because the standard requires that two separate values cannot have the same address. But the single byte at the &a location is, of course, not part of a itself; it's padding the compiler is forced to insert.

Shouldn't they both be null pointers?

No. Why should they be? The structs named a and b exist. The fact that they don't contain any data, doesn't count against their existence. &a is the address of a ; expecting &a to be null is like expecting to be able to do *(NULL) without invoking undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM