POV-Ray : Newsgroups : povray.off-topic : C++ classes and file i/o : Re: C++ classes and file i/o Server Time
5 Sep 2024 23:15:53 EDT (-0400)
  Re: C++ classes and file i/o  
From: Darren New
Date: 14 Apr 2009 00:55:57
Message: <49e4175d@news.povray.org>
stbenge wrote:
> Maybe I'm just working with a different kind of C++. I'm using a Mingw 
> compiler. Can the standards be that different? fread() only returns the 
> correct values when I clear the &xyz read variable to 0 first. I only 
> need to do this once, though.

The problem comes from ....

> be worried? Maybe I should create one or two extra Fields and display 
> them, just to be sure?

... you reading 2-byte values into ...

> They are four-byte integers, and this may be part of the previous 
> problem. This seems like the kind of issue which might bite me in the 
> @ss later if I don't follow standard procedure.

... 4-byte integers. You can't expect that to work properly.

You need to either make it
   val = buf[0] + 256 * buf[1]
or
   val = buf[1] + 256 * buf[0]
depending on the endian-ness of the values you've written. Try your code 
with a val of 64000 and see what you get. Or with a val of -10.

In other words, it works when you clear things to 0 first because the calls 
to fread() are only initializing part of the integers. You're reading 2 
bytes into a memory space allocated 4 bytes at a time, so whatever garbage 
was in the high bytes is getting left there.

> This sounds like good coding practice. I don't ever plan to feed it the 
> wrong files, but if I accidentally do, then at least I can crash the 
> program gracefully ;)

Exactly. You should always check your return values. Get in that habit, and 
you'll be in good shape. Also get in the habit of not assuming particular 
memory layouts and not assuming particular sizes of integers. It's good to 
get in the habit of not stepping outside the standard even if it happens to 
work on the machine you're on, because 3 years from now when you move to a 
different OS/CPU/whatever, you'll be surprised. (Indeed, even people on the 
68000 got surprised when their code was run on a 68020 and all of a sudden 
all 32 bits of an address register were significant, so all the folks 
storing flag bits in the top byte were screwed.) Pretend you don't actually 
know what the machine is doing underneath the definition of the language and 
you'll write better code. If you spend too long relying on particular 
implementation techniques, you'll never remember what's actually C and what 
happens to be MingW.

The folks with conficker installed would almost certainly have preferred 
that IE crash gracefully. :-)

-- 
   Darren New, San Diego CA, USA (PST)
   There's no CD like OCD, there's no CD I knoooow!


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.