Article View: comp.std.c
Article #4283Re: Variable length struct hack
From: Christopher R. Volpe
Date: Fri, 27 Oct 1995 13:18
Date: Fri, 27 Oct 1995 13:18
40 lines
2045 bytes
2045 bytes
In article <DH220v.9r@thinkage.on.ca>, dat@thinkage.on.ca (David Adrien Tanguay) writes:
>How is the following concept for strict conformance? (with appropriate context)
>
>struct s_t {
> int this, that;
> /* this structure has a variable length tail */
>};
>
>#define tail_of(p) ((char*) ((p)+1))
>
>void f(size_t tail_size) {
> struct s_t *sp = malloc(sizeof(*sp) + tail_size);
> char *the_tail_is = tail_of(sp);
> ...
>}
>
>If tail_size < sizeof(struct s_t), can tail_of() fail because of the +1?
>I.e., assuming pointers carry bounds, can the implicit cast from malloc to sp
>re-boundize the pointer value to an integral number of struct s_t's? Then the
>cast to char* in tail_of would produce a pointer with the truncated bounds so
>you still couldn't access the entire malloc'd object that way.
Correct. But all you need to do is change the definition of tail_of
as follows:
#define tail_of(p) ((char*)(void*)(p) + sizeof(*(p)))
This way, when we convert p to a void*, we get back the exact same pointer
returned by malloc. This pointer can be used to access an array of any object
type. So we cast it to char*, and then skip over all the chars that make up
the struct s_t definition. The resulting pointer value points into the middle
of the mallocced char array, right at the beginning of the tail. This is
strictly conforming.
--
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:
<46qm6e$bba@rdsunx.crd.ge.com>Path:
arc1-ca.pugleaf.net!bart.crd.ge.com!volpeReferences:
<463egk$jbb@nntp.Stanford.EDU> <DH0uG2.Ft@eskimo.com> <DH220v.9r@thinkage.on.ca>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: 27 Oct 1995 13:18:06 GMT Organization: GE Corporate Research & Development Sender: volpe@bart (Christopher R. Volpe) Distribution: world Message-ID: <46qm6e$bba@rdsunx.crd.ge.com> References: <463egk$jbb@nntp.Stanford.EDU> <DH0uG2.Ft@eskimo.com> <DH220v.9r@thinkage.on.ca> Reply-To: volpe@ausable.crd.ge.com NNTP-Posting-Host: bart.crd.ge.com