2017-06-27 52 views
0

親愛StackOverflow'ers,CPP - 未處理的異常的std :: bad_alloc的

我已經得到與C++編碼和我參加了一個項目中,我讀出4D SQL數據庫的信息到MySQL語法.sql文件然後由MySQL服務器執行。 我遇到以下問題;如果我用一個表運行CreateSQL函數,然後退出程序,它運行良好。

如果我環路CreateSQL函數創建的所有表的SQL,它無法與一個std :: bad_alloc的錯誤。

因爲我與C++非常新,我希望如果一些比較有經驗的C++程序員可以在可能發生這種錯誤的方向指向了我。 我(雛)的猜測是變量或這個時機不正確釋放,如下:

SQLFreeHandle(SQL_HANDLE_STMT, hStmt) ; 
SQLFreeHandle(SQL_HANDLE_DBC, hConn) ; 
SQLFreeHandle(SQL_HANDLE_ENV, hEnv) ; 

任何幫助將不勝感激。

完整的源代碼如下:

​​

編輯:繼從註釋弗朗索瓦的意見:

for(int i = 1 ; i <= numRows ; i++) 
{ 
// Datatypes 
// SQLGetData 

char buf[256]; 
SQLINTEGER numBytes ; 
newFile << createInsert(table); 
for(int j = 1 ; 
    j <= numCols ; 
    j++) 
{ 

    retCode = SQLGetData(

    hStmt, 
    j,   // COLUMN NUMBER of the data to get 
    SQL_C_CHAR, // the data type that you expect to receive 
    buf,   // the place to put the data that you expect to receive 
    255,   // the size in bytes of buf (-1 for null terminator) 
    &numBytes // size in bytes of data returned 

) ; 

    if(CHECK(retCode, "SqlGetData", false)) 
    { 
     retCode2 = SQLDescribeColA(hStmt, j, colName, 255, &colNameLen, &dataType, &columnSize, &numDecimalDigits, &allowsNullValues) ; 
     if(CHECK(retCode2, "SQLDescribeCol")) 
     { 
      //cout << dataType << endl; 
      if(dataType != 91) { 
       newFile << "'" << removeSlashes(removeSpecials(buf)) << "'"; 
      } 
      else if (dataType == 91) { 
       newFile << "date_format(str_to_date('" << fixDate(buf) << "', '%d-%m-%Y'),'%Y-%m-%d')"; 
      } 
     } 
    //Sleep(50); 
    } 
    if(j != numCols) { 
     newFile << ","; 
    } 

} 
newFile << ");\n"; 
cout << "Regel #" << i << " van tabel " << table << " is verwerkt." << endl; 

retCode = SQLFetch(hStmt) ; 
if(!SQL_SUCCEEDED(retCode)) 
{ 
    cout << "Tabel "+table+" is verwerkt." << endl; 
    printf("Regel %d is de laatste regel.\n", i) ; 
} 
} 
+0

[這'的std :: bad_alloc'參考](http://en.cppreference.com/w/cpp/memory/new/bad_alloc)可能有助於解釋什麼是什麼。你是正確的,它必須處理動態分配的內存,但不能釋放它。 –

+0

感謝您的快速回復,我會仔細研究一下! – Vexation

+0

如果您提供[MCVE],用戶更有可能關注您的問題。提供一個鏈接到您的代碼(不是直接提供問題)並提供如此大量的鏈接會阻止大多數用戶考慮您的問題。 –

回答

0

std::bad_allocnew當內存分配失敗,通常拋出因爲內存耗盡通常表示程序中某處存在內存泄漏。

你的功能createInsertcreateSelect都是通過動態分配散落,你不delete

char * array = new char[array_size]; 

而不是動態分配這樣,你應該使用std::stringoperator>>從一個ifstream提取和引導遠離任何動態分配,總是比手動分配更好的方法。


附註while(!file.eof())總是不好。

+0

非常感謝您對'while(!file.eof())'的提示,我不知道這一點。一般來說,非常感謝您的幫助! – Vexation