【问题标题】:Visual C++: Invalid allocation size. Why is this happening?Visual C++:分配大小无效。为什么会这样?
【发布时间】:2012-06-08 08:40:11
【问题描述】:

我是学习C++的过程。我在 VC++ 上调试我的一些代码时遇到了以下错误-

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

当调试器到达以下块时,该错误恰好发生:EDIT:我添加了整个 main 函数来帮助检查 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;
        }

【问题讨论】:

  • 我怀疑这与maxlen 是什么有关...?
  • 其中一个名字比maxlen长。
  • @Moo-Juice:我已经添加了与 main 相关的整个代码。
  • @molbdnilo:我使用的是长度为 15 个字符的字符串,所以我认为这是不可能的。

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


【解决方案1】:

你可能会看这条线:

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

你的意思可能是:

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

【讨论】:

  • maxlen 定义为size_type。我添加了更多相关代码,请看一下。
  • 从新代码中我可以看到 maxlen=0,确认您正在尝试分配负长度字符串。
  • er 这如何帮助推断;我试图分配一个负长度的字符串,我到底要纠正什么?
  • 我想要做的是简单地用计算出的空格数量填充所有列出的学生姓名,以便它们垂直对齐。首先找出最长名字的长度来计算空格在列表中,它存储在maxlen 中。那么对于每个学生的名字,有maxlen+1-students.name.size()空格,对于名字最长的学生,名字后面只有一个空格(maxlen+1-maxlen)。
  • 您尝试过 maxlen=(maxlen,x) 修复吗?
【解决方案2】:

在将 maxlen 初始化为 0 之后,您永远不会为它分配一个值。然后您会从该值中减去 1,从而给出一个负偏移量。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多