From: 643-408-1753@kylheku.com   
      
   On 2025-10-08, Bonita Montero wrote:   
   > Am 08.10.2025 um 08:35 schrieb Kaz Kylheku:   
   >> 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.   
   >>   
   >   
   > In a real language:   
      
   That HackerNews comment I alluded to actually arose in the context   
   of C++ code that was using struct hack.   
      
   The size is not know at compile time, so it cannot be a template   
   parameter.   
      
   It is also important that the entire object, header plus data,   
   is one memory allocation. It is less overhead. Also, given a   
   pointer to the structure, the pointer to the flexible array   
   data is just a displacement calculation: there is no additional   
   pointer to load to get to the data.   
      
   You should be glad you have the technique available in C++.   
      
   --   
   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)   
|