lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Gé Weijers wrote in
 <CAGj8prjC61=GGCf9q=kJu5YPqJvbOn7buRg+eRXeSKQhP4y=Pw@mail.gmail.com>:
 |On Tue, Nov 15, 2022 at 8:45 AM Steffen Nurpmeso <steffen@sdaoden.eu> \
 |wrote:
 |> Ah sigh, do not make me weird; now i had to look.  Well yes i also
 |> use that idiom, but then without any array field in the struct as
 |> such (ie alloc as much as needed, place the struct at the bottom
 |> and then ptr=&type[1] to point to thereafter).
 |
 |The "data[1]" field forces alignment constraints on the 'flexible' array at
 |the end of the structure. If you leave it off and use
 |"&type[1]" the pointer generated may actually not be correctly aligned for
 |the type of 'data'.

True..  Ok this is not Lua, but i normally use the mentioned
support macro(s).  And if not, and if the structure "is not
aligned" (in the meantime i no longer use a "PACKED" attribute for
structures and classes no more, to force alignment of 1 and
packing -- but i once did!), then i use several ALIGN_* macros to
get over that.  Ie (slightly cleaned)

  dmcp = CALLOC(ALIGN_Z(sizeof *dmcp) + sizeof(struct header));
  dmcp->dmc_hp = R(struct header*,ALIGN_Z(P2UZ(&dmcp[1])));

(Ie P2UZ is any-pointer-to-register-size-integer aka uinptr_t.
This still would break if dmcp would contain "long doubles"
/ 128-bit floating-point, then Z_OVER(), but luckily i personally
do not need to use floating-point.)

 |You may not notice on a PC or an advanced ARM processor, but not all
 |embedded CPUs can do misaligned accesses,
 |and they can be slower. You're definitely in undefined territory doing \
 |that.

Should not.  (I surely have seen dramatic performance impact for
unaligned memory accesses on x86, too.)

P.S.: sometimes all this syntax cruft causes bogus and flawed
programming behaviour of the author, which at times even gets
released.  But in general it works quite well.

--steffen
|
|Der Kragenbaer,                The moon bear,
|der holt sich munter           he cheerfully and one by one
|einen nach dem anderen runter  wa.ks himself off
|(By Robert Gernhardt)