Visual C ++:无效的分配大小。为什么会这样?

时间:2012-06-08 08:40:12

标签: c++ debugging visual-studio-2008 visual-studio-debugging

我是学习C ++的过程。我无法在VC ++上调试我的一些代码,但出现以下错误 -

Debug Error
*path to filename.exe*
Invalid allocation size:429496723 bytes.

当调试器到达以下块时,会出现错误:编辑:我添加了整个主函数,以帮助检查 maxlen 是否正在处理任何意外值(无但我注意到了)

int main(){

    vector <Student_info> students;

    Student_info record;

    string::size_type maxlen=0;// length of the longest name

    //read and store all the students data.

    //maxlen contains the length of the name of the longest student.

    while (read(cin,record)){
    // find the length of the longest name
        max(maxlen,record.name.size());
        //add the student record to the vector.

        students.push_back(record);
    }
    //arrange the records alphabetically.
    sort(students.begin(),students.end(),compare);// this may look weird but the fact that the names have to be compared is checked using the predicate.

        //write out the names and grades.


        for(vector<Student_info>::size_type i =0;i!=students.size();i++){

            //padding to ensure that there is vertical alignment.
            cout<<students[i].name<<string(maxlen+1-students[i].name.size(),' ');// debugger stops here!
            //compute grade.
            try{
                double final_grade=grade(students[i]);
                streamsize prec=cout.precision();
                cout<<setprecision(3)<<final_grade<<setprecision(prec);
            }
            catch(domain_error e){
            //catch error if hw vector is empty!

                e.what();

            }
            cout<<endl;

            }
        return 0;
        }

2 个答案:

答案 0 :(得分:8)

您可以查看以下行:

max(maxlen,record.name.size());

你的意思是否可能:

maxlen = max(maxlen,record.name.size());

答案 1 :(得分:3)

在将它初始化为0后,你永远不会为maxlen赋值。然后你将从中减去1给出负偏移量​​。

在你的第一个while循环中你可能想要......

   maxlen = max( maxlen, record.name.size() );