Sys V IPC: My final word
Bennett E. Todd III
bet at ecsvax.UUCP
Fri Feb 14 03:44:32 AEST 1986
In article <2666 at gatech.CSNET> hope at gatech.CSNET (Theodore Hope) writes:
> [...]
>The man pages for msgop(2) describe the msgbuf struct as containing
>
> long mtype; /* message type */
> char mtext []; /* message text */
>
> [...] The .h file defines
>
> struct msgbuf {
> long mtype;
> char mtext [1]; <- Notice: it says [1]
> }
> [...]
You should follow net.lang.c; this has popped up there. What you are
seeing is a C hack to permit variable-length structs. What you want to
say is
struct msgbuf {
long mtype; /* message type */
char mtext []; /* variable length, NULL-terminated */
}
but the C compiler croaks on that, so you use an array dimension of 1.
Note that the only member of a struct that can get away with being
varying length is the last member, and that only works because C doesn't
do array bounds checking. So anyway, how do you use it? Like so. Say,
perhaps, I am building messages in my own private array
char textbuff[MAXMTEXT];
then when I want to pass one in I roll up an empty struct msgbuf as
follows:
struct msgbuf *tmp_ptr;
char *malloc();
...
tmp_ptr = (struct msgbuf *) malloc(sizeof(struct msgbuf) +
strlen(textbuff));
if (tmp_ptr == NULL)
perror(...);
strcpy(tmp_ptr.mtext, textbuff);
I kind of like the technique; it allows you to use as much space as
needed and no more, without too much overhead or nuisance. Last I
recall, the consensus was that the technique should be reasonably
portable to any but the most rabidly pathological machine architectures.
-Bennett
--
Bennett Todd -- Duke Computation Center, Durham, NC 27706-7756; (919) 684-3695
UUCP: ...{decvax,seismo,philabs,ihnp4,akgua}!mcnc!ecsvax!duccpc!bet
More information about the Comp.unix
mailing list