Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c++ - 56 Expression: (unsigned)(c + 1) <= 256

I am making a hashing program that is counting the number of each instance of a word in a text file. This is my count function: I am getting an error when trying to run it.

56 Expression: (unsigned)(c + 1) <= 256

It appears as though it is crashing on the isalpha function when it is reading in the very first nonalpha garbage characters in the text file.

int
count(ifstream & fs,int size)
{
int find(const char *,int, int);

int f,i,l,y;
char ch,*p,s[maxs+1];

for(y = l = i = 0; i < size; i++)
{
    table[i].k = 0;
    table[i].p = nill;
}

p = s;

while(fs.get(ch))
{
    if(isalpha(ch))
    {
        if(l < maxs)
        {
            l++;
            *p++ = (char)(ch | 0x20);
        }
    }
    else
    {
        if(l)
        {
            *p = '';

            if(f = find(s,size,l) < 0)
            {
                return(f);
            }
            y += f;
            p = s;
            l = 0;
        }
    }
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks to me like isalpha is failing an assertion. Most likely (unsigned)(c + 1) <= 256 is the expression that is being asserted. It looks like this assertion is trying to ensure the value of c falls within [0, 255].

Assuming ch is a signed char and you try to store the value 128 in it, then pass it to isalpha, the left hand side of the assertion is going to evaluate to a very large number, causing it to fail.

128 can't be stored in a signed char, so the value of ch actually becomes -128, which is the signed representation of unsigned 128 (1000 0000 in binary). isalpha is taking ch as an int, so the (c + 1) is actually (-128 + 1), which becomes -127. This value is then cast to an unsigned integer, which turns into a very large value.

A solution is to change ch in your code to an unsigned char, if it's possible that it's value can be greater than 127.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...