C programming question
Tim Writer
tim-s/rLXaiAEBtBDgjK7y7TUQ at public.gmane.org
Wed Dec 24 17:41:03 UTC 2003
John Wildberger <wildberger-iRg7kjdsKiH3fQ9qLvQP4Q at public.gmane.org> writes:
> On December 23, 2003 06:45 pm, Matthew Rice wrote:
>
> > And this is better than:
> >
> > od -j 68 -N 2 -t x2 /dev/mem
> >
> > because??? ;)
>
> You don't get an argument from me on this. :-)
> I actually used this to verify my program. It is short, but not as much
> educational as writing a C- program.
> >
> > > short x;
> > > ssize_t size = read( fd, &x, 4 );
> >
> > Shorts aren't 4 bytes. Perhaps you should change the '4' to:
> >
> > sizeof(short)
> > or sizeof(x)
>
> It does not chane the result.
It may not change the result with your specific example but the code still
contains a bug. Think about what would happen if you wanted to use your
program to read the last two bytes of /dev/mem.
> I used the 'short' to get away from a printout with four bytes (high order
> first, followed by low order) which was confusing and not what was asked.
Matt was not objecting to your use of a short, he was objecting to you
reading 4 bytes into a two byte quantity. In your example, this could
overwrite valuable data on the stack (like the return address or other local
variables) causing your program to crash, report incorrect results, or behave
erratically. This is, of course, system and compiler dependent. In this
case, you got away with it probably because gcc added two bytes of padding
following the short.
A better way to write this is to use C99's exact size types (from
<inttypes.h>):
uint16_t x;
ssize_t size = read(fd, &x, sizeof(x));
And then you can print it with:
printf("%" PRIx16 "\n", x);
--
tim writer <tim-s/rLXaiAEBtBDgjK7y7TUQ at public.gmane.org> starnix inc.
905.771.0017 ext. 225 thornhill, ontario, canada
http://www.starnix.com professional linux services & products
--
The Toronto Linux Users Group. Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml
More information about the Legacy
mailing list