【发布时间】:2016-01-31 09:37:21
【问题描述】:
我为一个班级提交了这个程序,错误消息说有一些内存泄漏,但我找不到它们(我什至问过另一位教授)
这是错误信息:
==27796== HEAP SUMMARY:
==27796== in use at exit: 160 bytes in 2 blocks
==27796== total heap usage: 192 allocs, 190 frees, 21,989 bytes allocated
==27796==
==27796== 160 bytes in 2 blocks are definitely lost in loss record 1 of 1
==27796== at 0x402ADFC: operator new[](unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==27796== by 0x804D5C2: SweeperGrid::SweeperGrid(SweeperGrid const&) (in /tmp/grading20151030-8173-zfd6af-0/sweepertest)
==27796== by 0x804BF57: main (sweepertest.cpp:357)
以下是我使用 new 或 delete 的任何代码:
// 显式值构造函数
SweeperGrid::SweeperGrid(const int initialRows, const int initialCols, const int density){
if ((initialRows<5 || initialCols<5) || (density<25 || density>75)) {
throw out_of_range("Grid not large enough (number of rows or columns cannot be fewer than 5) or density is too low or high (must be between 25% and 75%)");
}
numRows = initialRows;
numColumns = initialCols;
numBombs = 0;
grid = new SweeperCell*[numRows];
for(int i=0; i <numRows; i++){
grid[i] = new SweeperCell[numColumns];
}
srand(time(0));
for(int i=0; i<numRows; i++){
for (int j=0; j<numColumns; j++){
if(rand()%100+1<density){
PlaceBomb(i, j);
}
}
}
}
// 复制构造函数
SweeperGrid::SweeperGrid(SweeperGrid const & source){
numRows=source.GetRows();
numColumns=source.GetColumns();
numBombs=source.GetBombs();
grid = new SweeperCell * [numRows];
for(int i=0; i < numRows; i++){
grid[i] = new SweeperCell[numColumns];
}
for(int i=0; i<numRows; i++){
for (int j=0; j<numColumns; j++){
grid[i][j] = source.At(i, j);
}
}
}
// 析构函数
SweeperGrid::~SweeperGrid(){
for(int i=0; i<numRows; i++){
delete [] grid[i];
}
delete [] grid;
}
// 功能:重载赋值运算符
void SweeperGrid::operator= (SweeperGrid const & source){
numRows=source.GetRows();
numColumns=source.GetColumns();
numBombs=source.GetBombs();
for(int i=0; i<numRows; i++){
delete [] grid[i];
}
delete [] grid;
grid = new SweeperCell * [numRows];
for(int i=0; i < numRows; i++){
grid[i] = new SweeperCell[numColumns];
}
for(int i=0; i<numRows; i++){
for (int j=0; j<numColumns; j++){
grid[i][j] = source.At(i, j);
}
}
}
【问题讨论】:
-
请也定义类。
-
老兄只要使用向量就不会泄露内存了。
-
在您的赋值运算符中,您删除的是在分配的网格中找到的行数,而不是在之前的网格中。
标签: c++ memory-management memory-leaks heap-memory minesweeper