🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4123

Pointer conversion and struct tricks

#4123
From: Igor Postelnik
Date: Tue, 26 Sep 1995 15:31
42 lines
1685 bytes
I have two somewhat related questions:

(1) Consider the following code segment:
	int *ip;
	void *vp1, *vp2;

	... some code where vp1 is made to point to valid memory ...

	ip = (int *)vp1;		/* 1 */
	vp2 = ip;		/* 2 */

Question: assuming vp1 is alligned properly to allow line 1, do vp2
and vp1 carry the same information after line 2. In general, is it
legal in ANSI C to cast from void * to int *, and then back to void *
without loss of information? Especially, in a case where int * and
void * are implemented differently by the underlying architecture.

(2) The second question may seem to be unrelated, but both came out of
the same discussion.

It is a widespread trick to implement variable length structures by
declaring

	struct x {
		int len;
		char data[1];
	};

and the doing

	struct x *p = (struct x *)malloc( sizeof struct x - 1 + length );

where length is the length of data you want to carry. Now, the C FAQ
says that this is not very kosher (per ANSI standard). However, it
refers to the ANSI Rationale, which seems to imply that this is fine.
Also, another variation of this trick is to declare tag data to be of
the maximum size you plan to use and then allocate just as much memory
as you need (i.e. less than sizeof struct x). Are these tricks legal
in ANSI C?

Thanks,
	Igor
Technical Details
Message-ID: <4496fg$t30@natinst.com>
Path: arc1-ca.pugleaf.net!natinst.com!usenet

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!natinst.com!usenet
From: igor@natinst.com (Igor Postelnik)
Newsgroups: comp.std.c
Subject: Pointer conversion and struct tricks
Date: Tue, 26 Sep 1995 15:31:40 GMT
Organization: National Instruments, Austin TX
Message-ID: <4496fg$t30@natinst.com>
NNTP-Posting-Host: babylon.natinst.com
X-Newsreader: Forte Free Agent 1.0.82