Article View: comp.std.c
Article #2196Re: struct hack
From: James Kanze
Date: Fri, 02 Oct 1992 21:07
Date: Fri, 02 Oct 1992 21:07
36 lines
2017 bytes
2017 bytes
I have been following this thread for a while, and since nobody else
seems to have said it, I will.
>> struct fred { int i; char s [1]; } *f;
>> char *s;
>>
>> /* ... */
>> f = malloc (sizeof f + strlen (ss));
>> f->s[1 /* or 2, or anything other than 0 */] ;
Despite all the assertions to the contrary, it seems to me that this
program does not conform to the ANSI C standards.
As is pointed out in previous posts, the pointer returned by malloc
points to an area big enough for the job. In fact, the following
should be legal:
char* p = malloc( sizeof( struct fred ) + strlen( ss ) ) ;
p += offsetof( struct fred , s ) ;
p[ 1 /* Or anything up to the end of the malloced memory */ ]
The problem with the example is that the pointer under consideration
is *not* the pointer returned from malloc, but rather the results of
the pointer expression f->s (which has a type of char*). Note that
this is definitely a pointer to an array object (sizeof( f->s ) == 1),
and so according to the ANSI standard, bounds checking is allowed.
In the reality, I suspect that any compiler that actually did this
would break a lot of code (including some of my own).
--
James Kanze GABI Software, Sarl.
email: kanze@us-es.sel.de 8 rue du Faisan
67000 Strasbourg
France
Technical Details
Message-ID:
<KANZE.92Oct2210740@slsvdnt.us-es.sel.de>Path:
arc1-ca.pugleaf.net!sparky!uunet!math.fu-berlin.de!news.netmbx.de!Germany.EU.net!ira.uka.de!slsvaat!josef!kanzeReferences:
<9209080014.AA03467@enet-gw.pa.dec.com> <1992Sep09.112101.1139@x.co.uk> <1992Sep10.153316.20804@awdprime.austin.ibm.com> <1992Sep19.225457.13353@jarvis.csri.toronto.edu>Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c Path: arc1-ca.pugleaf.net!sparky!uunet!math.fu-berlin.de!news.netmbx.de!Germany.EU.net!ira.uka.de!slsvaat!josef!kanze From: kanze@us-es.sel.de (James Kanze) Subject: Re: struct hack In-Reply-To: flaps@dgp.toronto.edu's message of 20 Sep 92 02:54:57 GMT Message-ID: <KANZE.92Oct2210740@slsvdnt.us-es.sel.de> Sender: news@us-es.sel.de Organization: SEL References: <9209080014.AA03467@enet-gw.pa.dec.com> <1992Sep09.112101.1139@x.co.uk> <1992Sep10.153316.20804@awdprime.austin.ibm.com> <1992Sep19.225457.13353@jarvis.csri.toronto.edu> Date: 2 Oct 92 21:07:40 Lines: 37