Discussion: about *long
Afficher un message
Vieux 05/02/2008, 15h29   #3
James Kanze
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: about *long

On Feb 5, 2:07 pm, Gianni Mariani <gi4nos...@mariani.ws> wrote:
> sam wrote:


> > I want to ask question about following:-
> > #define SIZE 6000
> > long ret=0x00001515;
> > char buf[SIZE+5];
> > *(long*)&buf[strlen(buf)]=ret;
> > what exactly happenning at the last line of code.


A programmer is proving himself incompetent?

> That is a type cast, dereference and assignment. Very
> non-portable code BTW - on some machines it will crash and on
> some it will arrange bytes differently.


Most importantly, here: the cast is a reinterpret_cast, which
always depends somewhat on the implementation. (Why the
original author chose to hide this critical information from us
by using a C style cast is another question.)

> Assuming that between the definition of buf and the last line, there is
> an initialization of buf taking place, what is happening is that it is
> placing at the end of the null terminated string in buf a long.


> e.g. if buf contained the sequence 'a', 'b', 'c', '\0', x, x, x, y then,
> assuming long is a 4 byte type, the nul and the locations marked as 'x'
> will be replaced with the contents of "ret" which could be 0x15, 0x15,
> 0, 0 -or- 0, 0, 0x15, 0x15 or some other machine dependant format of
> "long" (could be 64 bit or 16 bit, you jusy don't know).


Just a nit, but strlen() returns the length of the string
without the final '\0', so the final '\0' will be overwritten.
And long can't be 16 bits, since LONG_MAX must be at least
2147483647.

But those are just nits---as you say, you just don't know.

FWIW, on my machine, if buf is initialized with "abc" (e.g. by
string copy), the code crashes. (long is 8 bytes, and requires
8 byte alignment.)

--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
  Réponse avec citation
 
Page generated in 0,06461 seconds with 9 queries