[Gllug] Pointer arithmetic with void *

Tethys tet at accucard.com
Fri Aug 16 08:02:54 UTC 2002


>To avoid this you should go:
>
>	struct	foo	f;
>
>	....
>
>	memcpy((void*)&f, p, sizeof(f));
>	i = f.some_member;

That's not wise at all. Assume p points to a data stream consisting
of an 8-bit char followed by two 16-bit shorts and a 32-bit int.
That's 9 bytes. You'd define struct foo as:

	struct foo
	{
		char c;
		short s1;
		short s2;
		int i;
	}

Yet sizeof(f) is almost guaranteed to be larger than 9 on any modern
CPU, as the compiler will add in padding to get natural alignment.
In fact, I'm pretty sure the compiler is even free to reorder the
structure contents as it sees fit to best arrange the data given
the alignment requirements (note that if the compiler does this,
then it's possible to get the desired sizeof(f), but the values
of the members won't be what you expect...)

The only safe way to get data into a struct is either one member at
a time, or by a structure copy (i.e., assignment from another structure
of the same type).

>Some chips are not so forgiving - don't write CPU specific code

Agreed. Also, s/CPU/compiler/

Tet

-- 
Gllug mailing list  -  Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug




More information about the GLLUG mailing list