0

我正在學習C++的過程。 編輯:我被困調試一些我在VC++代碼,具有下列錯誤 -Visual C++:分配大小無效。這是爲什麼發生?

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; 
     } 
+0

我懷疑它是做什麼用'maxlen'是......? –

+0

其中一個名字比'maxlen'更長。 – molbdnilo

+0

@ Moo-Juice:我添加了與main關聯的整個代碼。 – KodeSeeker

回答

8

你可能看行(沒有,我雖然發現):

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

難道你的意思是:

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

* maxlen *被定義爲'size_type'。我添加了更多相關的代碼,看看。 – KodeSeeker

+0

從新代碼中,我可以看到maxlen = 0,確認您正在嘗試分配負長度的字符串。 – 2012-06-08 09:50:05

+0

呃如何幫助推斷; Im試圖分配一個負長度的字符串,以及我正確的是什麼? – KodeSeeker

3

你永遠值分配給它initliazing爲0。再後來你從給人一種負偏移減去1後MAXLEN。

內,您的第一個while循環,你可能想...

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