🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4241

Re: Variable length struct hack

#4241
From: Christopher R. Volpe
Date: Wed, 18 Oct 1995 23:57
54 lines
2530 bytes
In article <463lpa$qgo@newshost.lanl.gov>, tanmoy@qcd.lanl.gov (Tanmoy Bhattacharya) writes:
>
>1) Is the following portable?
>
>struct blah {
>  int num;
>  char data[10000];
>} *ptr = malloc (sizeof (struct blah) - 9000);

Practically speaking? Probably. Strictly Conforming? Probably not.

>
>Point is `Is malloc required to return space properly aligned for even an
>object which does not fit into the space provided?' i.e. is the result of
>malloc aligned for struct blah in this case.

First question: probably not. Second question: yes.
If you malloc, say, 3 bytes, malloc is not required to provide alignment for a
4-byte object, say an int. Since the above malloc request will typically
evaluate to about 1004 bytes (10000 for "data" + 4 for "num" - 9000), malloc
has to presume that you might eventually use that storage for an array of 251
ints.

>
>The standard says that the return value of malloc is suitably aligned so
>that it can be assigned to a pointer of any kind. I guess they meant `without
>information loss'. 

Since the return type is "void *", it is guaranteed that converting this type
to any other pointer-to-object-or-incomplete-type will not lose information.

>
>2) Is the following portable?
>ptr->data[0];

Practically speaking? Probably. Strictly conforming? Well, "ptr->data" is
equivalent to "(*ptr).data", which has the subexpression "*ptr", which
dereferences a pointer that points to an "object fragment", so to speak, so
I'd say it's probably not strictly conforming.

>
>Point is that the struct *ptr, and the array ptr->data does not actually
>exist (C has no concept of partial objects). So, do subexpression
>which occur in value contexts have to actually exist (*ptr is probably not in
>a value context, but ptr->data certainly is!) for the full expression to be
>valid? 

I think so.

--

Chris Volpe				Phone: (518) 387-7766 (Dial Comm 8*833
GE Corporate R&D			Fax:   (518) 387-6560
PO Box 8, Schenectady, NY 12301		Email: volpecr@crd.ge.com
Technical Details
Message-ID: <46449u$nb2@rdsunx.crd.ge.com>
Path: arc1-ca.pugleaf.net!bart.crd.ge.com!volpe
References: <463egk$jbb@nntp.Stanford.EDU> <463lpa$qgo@newshost.lanl.gov>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!bart.crd.ge.com!volpe
From: volpe@bart.crd.ge.com (Christopher R. Volpe)
Newsgroups: comp.std.c
Subject: Re: Variable length struct hack
Date: 18 Oct 1995 23:57:50 GMT
Organization: GE Corporate Research & Development
Sender: volpe@bart (Christopher R. Volpe)
Distribution: world
Message-ID: <46449u$nb2@rdsunx.crd.ge.com>
References: <463egk$jbb@nntp.Stanford.EDU> <463lpa$qgo@newshost.lanl.gov>
Reply-To: volpe@ausable.crd.ge.com
NNTP-Posting-Host: bart.crd.ge.com