From: 643-408-1753@kylheku.com   
      
   On 2025-10-08, pozz wrote:   
   > Il 08/10/2025 08:35, Kaz Kylheku ha scritto:   
   >> Jonas Lund of https://whizzter.woorlic.org/ mentioned this   
   >> trick in a HackerNews comment:   
   >>   
   >> Given:   
   >>   
   >> struct S {   
   >> // ...   
   >> T A[];   
   >> };   
   >>   
   >> Don't do this:   
   >>   
   >> malloc(offsetof(S, A) + n * sizeof (T));   
   >>   
   >> But rather this:   
   >>   
   >> malloc(offsetof(S, A[n]));   
   >>   
   >> It's easy to forget that the second argument of offsetof is a   
   >> designator, not simply a member name.   
   >>   
   >   
   > struct S {   
   > unsigned int size;   
   > unsigned char mode;   
   > unsigned char array[];   
   > }   
   >   
   > In a 32-bits integer machine, sizeof(struct S) is 8, because there are 3   
   > bytes of padding after mode and array is considered empty.   
   >   
   > Now I want to store 9 bytes in array[]. I could use:   
   >   
   > malloc(sizeof(struct S) + 9 * sizeof(unsigned char))=malloc(17)   
      
   Ah well, you can lead an ass to water ...   
      
   --   
   TXR Programming Language: http://nongnu.org/txr   
   Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal   
   Mastodon: @Kazinator@mstdn.ca   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   
|