f



Portable/strictly conforming alternative to the "struct hack" (?)

I believe I've found a way to achieve something like the well-known "struct=
 hack". I'm curoius if this strictly conforms to C89/C90 (I'm writing a lib=
rary and my goal is full, strict C89/C90 conformance.)

The main idea is: I allocate memory large enough to hold an initial struct =
and the elements of the array. The exact size is (K + N) * sizeof(array_bas=
e_type), where `K` is  large enough so that `K * sizeof(array_base_type) >=
=3D sizeof(the_struct)`, and `N` is the number of array elements.

Then, I use the pointer that `malloc()` returned to store `the_struct`, the=
n I use pointer arithmetic to obtain a pointer to the beginning of an array=
 of `N` elements of the array following the struct.

One line of code is worth more than a thousand words, so here is an impleme=
ntation:

    typedef struct Header {
        size_t length;
        /* other members follow */
    } Header;

    typedef struct Value {
        int type;
        union {
            int intval;
            double fltval;
        } v;
    } Value;

    /* round up to nearest multiple of sizeof(Value) so that a Header struc=
t fits in */
    size_t n_hdr =3D (sizeof(Header) + sizeof(Value) - 1) / sizeof(Value);

    size_t n_arr =3D /* arbitrary array size here */;
    void *frame =3D malloc((n_hdr + n_arr) * sizeof(Value));

    Header *hdr =3D frame;
    Value *stack_bottom =3D (Value *)frame + n_hdr;

My main concern is that the last two assignments (using `frame` as both a p=
ointer to Header and a pointer to Value) may violate the strict aliasing ru=
le. I do not, however, dereference `hdr` as a pointer to Value - it's only =
pointer arithmetic that is performed on `frame` in order to access the firs=
t element of the value array, so I don't effectively access *the same* obje=
ct using pointers of different types.

So, is this approach any better than the classic struct hack (which has bee=
n officially deemed UB), or is it UB too?
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
ISO
9/2/2013 9:08:39 AM
comp.lang.c.moderated 1019 articles. 0 followers. Post Follow

4 Replies
296 Views

Similar Articles

[PageSpeed] 38

On 2013-09-02, Árpád Goretity <arpad.goretity@gmail.com> wrote:
> I believe I've found a way to achieve something like the well-known "struct hack". I'm curoius if this strictly conforms to C89/C90 (I'm writing a library and my goal is full, strict C89/C90 conformance.)
>
> The main idea is: I allocate memory large enough to hold an initial struct and the elements of the array. The exact size is (K + N) * sizeof(array_base_type), where `K` is  large enough so that `K * sizeof(array_base_type) >= sizeof(the_struct)`, and `N` is the number of array elements.
>
> Then, I use the pointer that `malloc()` returned to store `the_struct`, then I use pointer arithmetic to obtain a pointer to the beginning of an array of `N` elements of the array following the struct.
>
> One line of code is worth more than a thousand words, so here is an implementation:
>
>     typedef struct Header {
>         size_t length;
>         /* other members follow */
>     } Header;

strange....

>     typedef struct Value {
>         int type;
>         union {
>             int intval;
>             double fltval;
>         } v;
>     } Value;
>
>     /* round up to nearest multiple of sizeof(Value) so that a Header struct fits in */

>     size_t n_hdr = (sizeof(Header) + sizeof(Value) - 1) / sizeof(Value);

that n_hdr expression looks kind of dodgy, basically it evaluates to 1, 
anyone who goes to such lengths to caclulate 1 is unlikley to have
discovered something special. After that  I stopped trying to understand 
your code

> So, is this approach any better than the classic struct hack (which has been officially deemed UB), or is it UB too?

Look at modern C compilers ...
this has been perfectly valid, well-behaved C since the 1999 standard:

struct clump {
    int      thing ;
    sometype data[];
	}

-- ⚂⚃ 100% natural

--- news://freenews.netfront.net/ - complaints: news@netfront.net ---
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Jasen
9/7/2013 4:24:26 AM
On 2013-09-07, Jasen Betts <jasen@xnet.co.nz> wrote:
> On 2013-09-02, Árpád Goretity <arpad.goretity@gmail.com> wrote:

>>     typedef struct Header {
>>         size_t length;
>>         /* other members follow */
>>     } Header;

>>     size_t n_hdr = (sizeof(Header) + sizeof(Value) - 1) / sizeof(Value);
>
> that n_hdr expression looks kind of dodgy, basically it evaluates to 1, 
> anyone who goes to such lengths to caclulate 1 is unlikley to have
> discovered something special. After that  I stopped trying to understand 
> your code

I am of course wrong - having ignored the "/* other members follow */"
comment. sorry.


-- 
⚂⚃ 100% natural

--- news://freenews.netfront.net/ - complaints: news@netfront.net ---
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Jasen
9/11/2013 10:26:11 PM
> anyone who goes to such lengths to caclulate 1 is unlikley to have 
discovered something special

Don't insult me.

> that n_hdr expression looks kind of dodgy, basically it evaluates to 1,

How do you know?

> Look at modern C compilers ... 
this has been perfectly valid, well-behaved C since the 1999 standard: 

Again, I don't like being like an uninformed moron. I know we have C99. I just want to support Visual "Crappy" studio which doesn't. Hence I can't use C99. That's all.
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
ISO
10/3/2013 6:37:02 PM
Árpád Goretity <arpad.goretity@gmail.com> writes:
>> anyone who goes to such lengths to caclulate 1 is unlikley to have 
> discovered something special
>
> Don't insult me.
>
>> that n_hdr expression looks kind of dodgy, basically it evaluates to 1,
>
> How do you know?
>
>> Look at modern C compilers ... 
> this has been perfectly valid, well-behaved C since the 1999 standard: 
>
> Again, I don't like being like an uninformed moron. I know we have
> C99. I just want to support Visual "Crappy" studio which
> doesn't. Hence I can't use C99. That's all.

When you post a followup, your newsreader should automatically
insert an attribution line, so that readers can tell who wrote what.
Please don't delete it.

You quote an article posted by Jasen Betts on September 6, but the
headers indicate that you replied to another article that he posted
on September 11, in which Jasen wrote:

| I am of course wrong - having ignored the "/* other members follow */"
| comment. sorry.

It's possible you didn't see that; this is a moderated group, which can
do funny things with headers and message-ids (and I'm too lazy to track
it down further).

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
Working, but not speaking, for JetHead Development, Inc.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
comp.lang.c.moderated - moderation address: clcm@plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.
0
Keith
10/8/2013 9:38:02 PM
Reply:

Similar Artilces:

["a", "b", "c", "d"] to "a, b, c, d"?
I want to process each element of an array, but the last element should be handled special. Here is an example: def p_ary(ary) str = "" ary.each do |elem| str << elem << ", " end str.chomp!(", ") str end so p_ary(["a", "f", "x", "test"]) produces "a, f, x, test". The code works, but isn't there an easier and more general way for this behaviour? martinus On Tue, 06 Apr 2004 04:23:22 -0700, Martin wrote: > I want to process each element of an array, but the last ele...

""""""""""""""""""""""ADD ME""""""""""""""""""""
Hi , Hope you are doing great. Please let me take this opportunity to introduce myself, Iam Karthik working with BhanInfo Inc, a NY based company. We have consultants on our bench on various technologies, my request is to add me to your distribution list and kindly do send me the requirements. i have the below list available 1. Mainframe 2. Java 3.. Financial Analyst 4. Data Architect If there is any vendor ship agreement which has to be signed then I would like to take an opportunity to represent my company and expect your cooperation... We look forward to build a ve...

"""""""""ADD ME""""""""""
Hi , Hope you are doing great. Please let me take this opportunity to introduce myself, Iam Karthik working with BhanInfoi Inc, a NY based company. We have consultants on our bench on various technologies, my request is to add me to your distribution list and kindly do send me the requirements. i have the below list available 1. Mainframe 2. Java 3.. Financial Analyst 4. Data Architect If there is any vendor ship agreement which has to be signed then I would like to take an opportunity to represent my company and expect your cooperation... ...

What does "Standard C", "K&R C" , "ANSI C" mean?
I am just wondering what the following terms usually mean: 1) "Standard C" 2) "K&R C" 3) "ANSI C" I am pretty sure "ANSI C" usually refers to the C89 standard, but what about the other two? What is the "saying" for C99 standard? Thank you On 17 Jan 2005 21:26:42 -0800, "Luke Wu" <LookSkywalker@gmail.com> wrote in comp.lang.c: > I am just wondering what the following terms usually mean: > > 1) "Standard C" The current version of the C language standard. This is now known as "ISO/IEC 9899:19...

Urgent Requirement in """""""""""""NEW YORK""""""""""""""""
Hello Partners, Please find the requirement below. Please send the updated resume along with rate and contact no. REQ#1: Title : Java Developer ( Rating Project) Duration : 6 months Rate : open Location : NY strong java, WebLogic 9.2, Web Services, Oracle REQ#2: Title : Java Developer Duration : 4 months Rate : open Location : NY Strong java, SQL REQ#3: Title : VB.Net Consultant Location : NY Duration : 4 months Rate : open Primarily looking at someone who has Excel, VB.net a...

"struct hack" in C++0x?
Will the "struct hack" (incomplete/var-len struct type) which C99 formally included be included in C++0x? My compiler already allows it but issues a warning. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] On 5 juin, 19:53, "Tony" <t...@my.net> wrote: > Will the "struct hack" (incomplete/var-len struct type) which C99 formally > included be included in C++0x? My compiler already allows it but issues a > warning. No. This breaks the object model. Objects ar...

"If then; if then;" and "If then; if;"
I have a raw data set which is a hierarchical file: H 321 s. main st P Mary E 21 F P william m 23 M P Susan K 3 F H 324 S. Main St I use the folowing code to read the data to creat one observation per detail(P) record including hearder record(H): data test; infile 'C:\Documents and Settings\retain.txt'; retain Address; input type $1. @; if type='H' then input @3 Address $12.; if type='P' then input @3 Name $10. @13 Age 3. @16 Gender $1.; run; but the output is not what I want: 1 321 s. main H 2 321 s. main P Mary E 21 F 3 321 s...

about "++" and "--"
why this program snippet display "8,7,7,8,-7,-8" the program is: main() { int i=8; printf("%d\n%d\n%d\n%d\n%d\n%d\n",++i,--i,i++,i--,-i++,-i--); } > why this program snippet display "8,7,7,8,-7,-8" Ask your compiler-vendor because this result is IMHO implementation-defined. Check this out: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.15 http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.16 Regards, Irina Marudina fxc123@gmail.com wrote: > why this program snippet display "8,7,7,8,-7,-8&q...

"or" and "and"
Hi, I'm just getting to discover ruby, but I find it very nice programming language. I just still don't understand how the "or" and "and" in ruby... I was playing with ruby and for example made a def to print Stem and Leaf plot (for those who didn't have a statistics course or slept on it, e.g. http://cnx.org/content/m10157/latest/) Here is the Beta version of it: class Array def n ; self.size ; end def stem_and_leaf(st = 1) # if st != (2 or 5 or 10) then ; st = 1 ; end k = Hash.new(0) self.each {|x| k[x.to_f] += 1 } k = k.sort{|a, b| a[0].to_f <=&g...

why "::", not "."
Why does the method of modules use a dot, and the constants a double colon? e.g. Math::PI and Math.cos -- Posted via http://www.ruby-forum.com/. On Oct 26, 2010, at 01:48 , Oleg Igor wrote: > Why does the method of modules use a dot, and the constants a double > colon? > e.g. > Math::PI and Math.cos For the same reason why inner-classes/modules use double colon, because = they're constants and that's how you look up via constant namespace. Math::PI and ActiveRecord::Base are the same type of lookup... it is = just that Base is a module and PI is a float....

"my" and "our"
Hi, while testing a program, I erroneously declared the same variable twice within a block, the first time with "my", the second time with "our": { my $fz = 'VTX_Link'; .... ( around 200 lines of code, all in the same block) our $fz = 'VTX_Linkset'; ... } So the initial contents of the $fz declared with "my" is lost, because "our" creates a lexical alias for the global $fz, thus overwriting the previous "my" declaration. It was my error, no question. But I wonder why Perl doesn't mention this - even with "use s...

"/a" is not "/a" ?
Hi everybody, while testing a module today I stumbled on something that I can work around but I don't quite understand. >>> a = "a" >>> b = "a" >>> a == b True >>> a is b True >>> c = "/a" >>> d = "/a" >>> c == d True # all good so far >>> c is d False # eeeeek! Why c and d point to two different objects with an identical string content rather than the same object? Manu Emanuele D'Arrigo wrote: >>>> c = "/a" >>>&...

"out" and "in out"
Hi i found the following explaination: In Ada, "in" parameters are similar to C++ const parameters. They are effectively read-only within the scope of the called subprogram. Ada "in out" parameters have a reliable initial value (that passed in from the calling subprogram) and may be modified within the scope of the called procedure. Ada "out" parameters have no reliable initial value, but are expected to be assigned a value within the called procedure. What does "have no reliable initial value" mean when considering the "out" parameter? By c...

Urgent Requirement for """""""""""""""INFORMATICA DEVELOPER"""""""""""""
Hello Partners, How are you ? Please find the requirements below. Title: Database/ETL Developer Duration: 6 months Location: NY Exp: 7+ Locals preferred Database/ETL requirements (Mandatory) Candidate must have worked with financial instruments, preferably Mutual Funds but, Equities are also ok. PL/SQL - packages, Stored procs, Functions, Aggregate functions, Pipelined Functions Informatica 8.6 - especially complex mappings, complex maplets, complex workflows, transformations Oracle 10g/11g Unix/Linux shell scripting ...

Web resources about - Portable/strictly conforming alternative to the "struct hack" (?) - comp.lang.c.moderated

Resources last updated: 2/8/2016 10:00:49 PM