[Gllug] Pointer arithmetic with void *

Alain Williams addw at phcomp.co.uk
Fri Aug 16 08:14:22 UTC 2002


On Fri, Aug 16, 2002 at 09:02:54AM +0100, Tethys wrote:
> 
> >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).

Sorry - I was (perhaps erroniously) got the impression that this is indeed
what had happened. I was trying to make the point that just because you
can access a file as memory, there are things to beware.

> >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

-- 
Alain Williams

#include <std_disclaimer.h>

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




More information about the GLLUG mailing list