Re: Program crashes when running it outside dev environment



David Tiktin <dtiktin@xxxxxxxxxxxxxxxxxxxxxxxx> writes:
On 08 Jun 2007, Richard Heathfield <rjh@xxxxxxxxxxxxxxx> wrote:
David Tiktin said:
On 08 Jun 2007, Richard Heathfield <rjh@xxxxxxxxxxxxxxx> wrote:
So my suggestions would be:

1) crank up your warning level to the max
2) turn off any extensions you can live without
3) fix every single diagnostic message, and *never* with a cast

I'm with you right up to the last clause. Are you saying you
never actually *need* a cast?

No, there are (rare) occasions when you do need a cast. But I
don't know of any occasion where you *need* a cast AND omitting it
violates a constraint or constitutes a syntax error. So adding a
cast is not the right way to fix a diagnostic message. If the
choice is between adding bad code and putting up with a bad
warning, I'll live with the bad warning.

But now you're changing your advice. You get diagnostics for things
other than constraint violations and syntax errors. On the highest
warning levels, you may well get a diagnostic on code like this:

char * ptr = buffer;
int c;

while ((c = getchar()) != EOF)
{
*ptr++ = c;
}

diag.c(73) : warning C4244: '=' : conversion from 'int ' to 'char ',
possible loss of data

That's with MSVC 6.0 and -W4.

Do you think loss of precision diagnostics are "bad warnings"? (I
don't.) Shouldn't we fix this with a cast?

*ptr++ = (char) c;

If not, what do you suggest? If we do nothing, we'll have to think
about that warning every time we build, because an *actual* loss of
precision is often a serious bug.

c is of type int. We know that it's a value returned by getchar(),
and that it's not equal to EOF, so it must be within the range of
unsigned char, 0..UCHAR_MAX.

Suppose UCHAR_MAX==255 and char is signed, with CHAR_MAX==127, and
suppose c==200. Then the conversion of the value 200 to type char
either yields an implementation-defined value or raises an
implementation-defined signal (C99 6.3.1.3p3).

(In most implementations the conversion will yield a "sensible"
result, most likely -55.)

I suspect that's not what MSVC is complaining about; my guess is that
it would produce the same warning if ptr were declared as unsigned
char*. (And of course the code invokes UB if you overflow the buffer;
it's like gets(), but reading an entire file rather than a single
line.)

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages