我必須做某種項目,並且我被卡住了。我得到一個bad_alloc錯誤。我檢查了很多次代碼,嘗試谷歌一些解決方案,但仍然沒有,這就是爲什麼我寫在這裏。事情是程序正常運行,但在任務管理器,他的內存使用率提高到2GB(這是限制我知道),然後它崩潰。程序需要檢查分配空間和複製變量的時間。以下是部分代碼:創建20k陣列時的bad_alloc
class Table
{
int *tablica;
int size;
public:
Table()
{
tablica = NULL;
size = 0;
}
~Table()
{
delete tablica;
size = 0;
}
int *push_back(int val)
{
int *temp = new int[size];
if(size % 10 == 0)
{
for(int i = 0; i < size; i++)
temp[i] = tablica[i];
tablica = new int[size + 10];
for(int i = 0; i < size; i++)
tablica[i] = temp[i];
}
tablica[size] = val;
size++;
delete []temp;
return tablica;
}
void test()
{
LONGLONG measure[100][6];
LARGE_INTEGER performanceCountStart, performanceCountEnd;
int cpy_tab [20000];
for(int j = 0; j < 100; j++)
{
for(int i = 0; i < 20000; i++)
cpy_tab[i] = rand() % 10000 - 10000;
performanceCountStart = startTimer();
for(int i = 0; i < 500; i++)
{
push_back(cpy_tab[i]);
}
performanceCountEnd = endTimer();
measure[j][0] = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
cout<<j<<"."<<measure[j][0]<<endl;
delete []tablica;
size = 0;
performanceCountStart = startTimer();
for(int i = 0; i < 2000; i++)
{
push_back(cpy_tab[i]);
}
performanceCountEnd = endTimer();
measure[j][1] = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
cout<<j<<"."<<measure[j][1]<<endl;
delete []tablica;
size = 0;
performanceCountStart = startTimer();
for(int i = 0; i < 4000; i++)
{
push_back(cpy_tab[i]);
}
performanceCountEnd = endTimer();
measure[j][2] = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
cout<<j<<"."<<measure[j][2]<<endl;
delete []tablica;
size = 0;
performanceCountStart = startTimer();
for(int i = 0; i < 8000; i++)
{
push_back(cpy_tab[i]);
}
performanceCountEnd = endTimer();
measure[j][3] = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
cout<<j<<"."<<measure[j][3]<<endl;
delete []tablica;
size = 0;
performanceCountStart = startTimer();
for(int i = 0; i < 14000; i++)
{
push_back(cpy_tab[i]);
}
performanceCountEnd = endTimer();
measure[j][4] = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
cout<<j<<"."<<measure[j][4]<<endl;
delete []tablica;
size = 0;
performanceCountStart = startTimer();
for(int i = 0; i < 20000; i++)
{
push_back(cpy_tab[i]);
}
performanceCountEnd = endTimer();
measure[j][5] = performanceCountEnd.QuadPart - performanceCountStart.QuadPart;
cout<<j<<"."<<measure[j][5]<<endl;
delete []tablica;
size = 0;
}
}
解決這個問題的任何想法都是值得的!
你不能給我們提供一個簡短的例子嗎?嵌套for循環出了什麼問題?真的有必要再次複製和粘貼這麼多代碼嗎? – xmoex
如果您懷疑有內存泄漏,請通過'valgrind'運行並查看另一端出現的內容。此外,請嘗試將示例的大小減小到可以重現問題的最小可編譯示例。你會經常發現,在試圖隔離這個最小的例子時,你已經發現了答案。 – merlin2011
請先調試並縮小您的問題。同樣使用像valgrind這樣的內存泄漏檢測器會是一個好主意。很可能你在某處泄漏,消耗的內存意外地累積。 –