1

I have this as my basic code.

struct TABLE
{
    unsigned char a[2];
    unsigned char b[8];
    unsigned short c;
};

The best way I have of describing this is, I can successfully read from a file and place the data into &TABLE. I have read the data here and it is all good.

However,

&TABLE.a = 0x0000FF00
&TABLE.b = 0x0000FF03
&TABLE.c = 0x0000FF0C

&TABLE.c should be 0x0000FF0B.

What gets really interesting is if I change, b to [7] from [8]. &Table.c then returns 0x0000FF0A

What is the logic here?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    Provide some [mre] in your question. Compile your C++ code with `g++ -Wall -Wextra -g`. Use the [GDB](https://www.gnu.org/software/gdb/) debugger to understand the behavior of your program. Perhaps use the [Clang static analyzer](https://clang-analyzer.llvm.org/). Consider using [sqlite](https://sqlite.org/) – Basile Starynkevitch Jan 18 '21 at 09:31
  • `&TABLE.b = 0x0000FF03`, are you sure? That doesn't make sense to me. I expect it to be `0x0000FF02`. I don't understand why there's a byte of padding between `a` and `b`. Please provide a [mre]. – John Kugelman Jan 18 '21 at 09:33
  • Yes, I double checked. – user6901898 Jan 18 '21 at 09:34
  • you could try explicitely set alignment of those chars, as for ex. `unsigned char alignas(2) a[2];` and `unsigned char alignas(2) b[8];` – StPiere Jan 18 '21 at 09:37
  • 1
    The strange behavior with `[7]` is explained by [alignment](https://stackoverflow.com/questions/38875369/what-is-data-alignment-why-and-when-should-i-be-worried-when-typecasting-pointe). See the link for a detailed explanation. – John Kugelman Jan 18 '21 at 09:37
  • I can't provide a sample because it's being done on another computer and my net access is just a mobile phone. – user6901898 Jan 18 '21 at 09:37
  • A minimal example would just be a struct and a `main` that prints the addresses of its members. That can be entered on a phone without much trouble (after you have verified its misbehaviour on the actual computer, of course). – molbdnilo Jan 18 '21 at 09:42
  • 2
    You could prepare an MCVE in an online compiler like e.g. [coliru](http://coliru.stacked-crooked.com/). – Scheff's Cat Jan 18 '21 at 09:42
  • To solve alignment issues as well as big/little endianess one may resort to boost's serialization. https://www.boost.org/doc/libs/1_64_0/libs/serialization/doc/index.html – kreuzerkrieg Jan 18 '21 at 11:22

1 Answers1

0

What was needed was

__attributes__ ((packed))

Thankyou to everyone and the person who mentioned alignments so I could go off and read into that. :)