...
(See also undefined behavior 113 of Appendix J.)
Compliance with this rule is complicated by the fact that the char
data type can, in any implementation, be signed or unsigned.
...
Noncompliant Code Example
This noncompliant code example may pass invalid values to the isspace()
function:On implementations where plain char is signed, this code example is noncompliant because the parameter to isspace()
, *t
, is defined as a const char *
, and this value may not be representable as an unsigned char
.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <ctype.h> #include <stddef.h> ptrdiffsize_t count_preceding_whitespace(const char *s) { const char *t = s; /* Possibly *t < 0 */size_t length = strlen(s) + 1; while (isspace(*t) && isspace(*tt - s < length)) { ++t; } return t - s; } |
The argument to isspace()
must be EOF
or representable as an unsigned char
; otherwise, the result is undefined.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <ctype.h> #include <stddef.h> ptrdiffsize_t count_preceding_whitespace(const char *s) { const char *t = s; size_t length = strlen(s) + 1; while (*t && isspace((unsigned char)*t) && (t - s < length)) { ++t; } return t - s; } |
Risk Assessment
Passing values to character handling functions that cannot be represented as an unsigned char
results in undefined program behavior.
...