-2

"Run-Time Check Failure #2 - Stack around the variable 'id' was corrupted."上车while condition。我不知道!是什么导致了这个错误?

void Term::set_id()
{
    char id[Term::ID_LENGTH];
    do
    {
        cout << "\n\nEnter the term id(like 90911): ";
        cin >> id;
    }while(valid_id(id) != true);
}

bool Term::valid_id(char *id)
{
    //counting how many chars id has got:
    int n=0;
    for(char* str=id; *(str+n)!=0; n++);

    if(n!=Term::ID_LENGTH)
        return false;

    //checking that id consist of digits only
    int i=0;
    for( char* str=id; (*(str+i)>=48 && *(str+i)<=57) && i<Term::ID_LENGTH; i++);
    if(i<Term::ID_LENGTH)
        return false;

    int fy= (*(id) - 48) * 10 + (*(id+1) - 48);//former year
    int ly= (*(id+2) - 48) * 10 + (*(id+3) - 48);//latter year
    int t= *(id+4) - 48;//term number
    if(ly - fy != 1)//any difference other than 1
        return false;
    if(!(t==1 || t==2 || t==0))//t==0 is for summer term
        return false;

    return true;
}
4

2 回答 2

2

这段代码看起来像一个简单的数组溢出。如果您没有设置流来限制要读取的字符数,std::cin >> strstr作为char数组或指向的指针char是 C 的 C++ 版本:gets()width()

char id[Term::ID_LENGTH];
std::cin.width(Term::ID_LENGTH); // <-- without this you are prone to array overrun!
if (std::cin >> id) {
    // deal with a successful read
}

您应该考虑将std::string其用于字符串的输入:

std::string id;
if (std::cin >> id) {
    // deal with a successful read
}
于 2012-12-31T02:26:08.487 回答
0

Term::ID_LENGTH忘记计算'\0'的问题的根源。

于 2012-12-31T03:54:19.857 回答