[英]CPP - Unhandled exception std::bad_alloc
親愛的StackOverflow'ers,
我一直在使用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 ) ;
}
}
std::bad_alloc
無法分配內存時,它會被new
拋出,通常是由於內存耗盡,通常表明程序中某處發生了內存泄漏。
您的函數createInsert
和createSelect
都被不delete
動態分配所createSelect
:
char * array = new char[array_size];
與其像這樣動態分配,不如使用std::string
和operator>>
從ifstream
提取並避免任何動態分配,總有一種比手動分配更好的方法。
旁注, while(!file.eof())
總是不好的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.