Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

address of a reference of packed member is not equal to address of packed member? [duplicate]

Tags:

c++

I compiled this program by g++. And it printed "unequal".
And it prints "equal" if I don't use "packed" attribute.
I don't know how "packed" attribute cause the differnece.

By the way, executable built by clang++ prints "equal".

#include <iostream>

struct __attribute__ ((packed)) Packed {
  char a;
  int b;
  int c;
  char d;
};

void test(const int &i, int *ptr) {
  std::cout << ((&i == ptr) ? "equal" : "unequal") << std::endl;
}

int main () {
  Packed p;
  p.c = 1;
  test(p.c, &p.c);
  return 0;
}
like image 561
eddie kuo Avatar asked Jan 28 '26 01:01

eddie kuo


1 Answers

When compiling with GCC or CLANG, there is a warning saying that taking address of packed member of 'Packed' may result in an unaligned pointer value which means that behavior of your code is unspecified. That's why you have different outputs when compiling with GCC and CLANG.

What does the __attribute__ ((packed)) mean?

The packed variable attribute specifies that a structure field has the smallest possible alignment. That is, one byte for a variable field, and one bit for a bitfield, unless you specify a larger value with the aligned attribute.

Why not to take the address of a packed member?

Taking the address of a packed member is dangerous since the reduced alignment of the pointee is lost. This can lead to memory alignment faults in some architectures if the pointer value is dereferenced.

References:

  • Warn when taking address of packed member
  • __attribute__((packed)) variable attribute
like image 82
NutCracker Avatar answered Jan 29 '26 15:01

NutCracker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!