signed vs unsigned pointer warning

Jamie Lokier jamie@shareable.org
Mon Sep 27 02:04:00 GMT 2004


Dave Korn wrote:
>   As I said, I think the standard makes it quite clear that you can pass -1
> and any unsigned char (0....255) value.  It seems to me to say quite clearly
> that if you have a signed char variable which is negative and you pass it to
> the ctype function and allow it to be sign-extended by the implicit argument
> promotion rules then you have supplied an out-of-range value to the
> function.

This is a real typical bug.  Just recently a bug was found in
curl-library, quite a popular little library, which calls
isspace(char).  The bug was missed for a long time, as it is only
triggered with characters with the MSB set, which do not occur often
in HTTP headers.

Their fix was to change the program to use "unsigned char" strings,
rather than change all the callers of isspace() as the latter change
might not be preserved by future programmers who don't know why the
cast in "issspace((unsigned char) c)" is necessary.

I must admit that I hadn't realised it was necessary and I have
written a lot of C (but I never use the is* functions anyway, so it's
never arisen for me).

I suspect quite a lot of programmers write "isspace(c)" and
"isalnum(c)" et al using a "char" argument, not realising they have
sometimes written buggy code - and it passes testing in many cases.

This is a reason why GCC should issue a signedness warning.

>   Anyway, I only gave this particular example as an illustration to back up
> my argument that the incompatibility between signed and unsigned chars is
> not theoretical but very very real and does very much occur in practice as
> it is very very common for char-sized arguments to be promoted to int sized
> and the two types behave significantly differently when this happens.
> That's all.

I agree with you, except that the real practical problems arise from
promotion to wider types, not operations involving just chars of
various signedness.

I agree with Linus that it's common to mix "char" with "unsigned char"
in real code, and warning about calling strlen(unsigned char) would be
too much.

The balance where the warning is useful is that it should warn about
errors such as calling "isspace()" with "char" or "signed char", but
_not_ warn about calling "strlen()" and "memcpy()" with "unsigned
char", or assigning a string constant to an "unsigned char *".

-- Jamie



More information about the Gcc mailing list