"grid" <pr******@gmail .com> wrote in message
news:Fj******** ****@news.oracl e.com...
The above code is broken. You attempt to store 4 chars/bytes
(1+strlen("abc" )==4) to the variable c, but you don't know whether c
(pointer to a char) is big enough to hold 4 chars/bytes. On some
platforms it can be 2 or even 1, hence you're risking to overwrite something else.
I gave the example for my particular machine/hardware just to make it a
point that this might not be a portable code.
It's not portable. It's portable around your machine's hard drive, but not
much further :) Or you should probably ask such portability and undefined
behavior questions at comp.lang.c.x86 or something like that :)
But apart from that, is it
guaranteed to function as intended where the pointer sizes are 4 bytes
or more.
I see no good reason for such code to exist at first place. Perhaps you
could tell me it, if there is.
It's much more easier and portable to declare a local 4-char array. If you
need to use that space either for a pointer or for an array of 4 chars (one
of them at a time), there's a union keyword for that.
Also writing past 4 bytes on a machine with 4 byte pointers dosent seem
to affect,though I am aware that undefined behaviour can really be
anything and that could also mean that it dosent manifests itself at
all.But this kind of non-compliant behaviour probably compels people to
write non-portable code in the first place rather than any significant
gain in efficiancy.
Unportable code is the result of not following the standard (usually not
knowning anything about it and not reading good books that were written with
the standard in mind or not paying attention to those important details) but
instead making own assumptions and relying on something that might or might
not be true. If there's a need for any hardware/CPU-specific code, the
proper way of doing it is to define the API and put portable code on one
side of it and that platform specific code on the other side and never move
a tiny bit of it to the portable part. Unportable code is mixing portable
things with non-portable. Often times those non-portable things are due to
writing say 4 when it must be sizeof(int) or sizeof(int*), improperly
aligning data, improperly calculating sizes of structures and offsets of
their members, reading/writing integers as bytes with big/little endian
problems, ignoring casting to long in multiplication of ints (ignoring the
fact that int and long aren't necessarily types of the same physical size),
etc. The thing is, many books don't mention many practical things and hence
the programmer must invent some way to them, often a quick and durty
non-portable hack.
Alex