[英]Memory leak in a 2D array
我有一堂課:
class Land{
public:
~Land() { if(map != nullptr) Clean(); }
bool Create();
void PrintMap() const;
void Clean();
private:
int rows = 0, columns = 0;
int **map = nullptr;
bool CorrectDimensions() const;
void CreateMap();
bool FillMap();
};
bool Land::Create() {
//
printf("Matrix size:\n");
if(scanf("%d %d", &(this->columns), &(this->rows) ) != 2 || !CorrectDimensions() )
return false;
CreateMap();
printf("Values:\n");
return FillMap();
}
void Land::CreateMap() {
//
this->map = new int*[rows];
for(int column = 0; column < this->rows; column++)
map[column] = new int[this->columns];
}
bool Land::FillMap() {
//
for(int row = 0; row < this->rows; row++) {
for(int column = 0; column < this->columns; column++) {
if( ! scanf("%d", &(this->map[row][column]) ) ) {
return false;
}
}
}
return true;
}
void Land::Clean() {
//
for(int row = 0; row < this->rows; row++)
delete [] this->map[row];
delete [] this->map;
}
而我的司機:
int main() {
//
Land l;
if( ! l.Create() ) {
IncorrectInput();
return 1;
}
l.PrintMap(); //prints correct output
}
我怎么想我的程序應該工作:
false
從而完成程序。 內存尚未動態分配(停留在nullptr
),沒有問題。 calloc
創建2D數組 (我知道我正在將C與C ++混合使用,想使用class和vector
不可用)。 Create()
是否提前結束(在calloc
之前),因此我默認將int **map
初始化為nullptr
。 如果我分配了, map
將不再是nullptr
,將需要釋放。 否則,析構函數應該free
,這就是Clean()
所做的。 Clean()
我遵循動態分配和釋放的做法。 calloc
和free
遵循相反的模式。 調試確認已調用了多少calloc
已調用了許多free
。 有了所有這些, valgrind
仍然會報告錯誤(無法reachable
,實際錯誤)。 具體來說: total heap usage: 184 allocs, 23 frees
。 是什么導致了此錯誤,我錯過了什么?
編輯:初始化的rows
和columns
成員。 使用C ++ new
和delete
更改了calloc()
。
沒有內存泄漏。 calloc
不會引發異常。
順便說一句,在Land::CreateMap
和其他地方檢測到了空指針引用。 不要忘記檢查calloc
返回值
例如,
class foo {
int* p1;
int* p2;
foo()
{
p1 = new int;
p2 = new int;
}
~foo()
{
delete p1;
delete p2;
}
};
int main()
{
foo val;
}
在foo
Ctor中,當p2 = new int;
拋出異常, foo
Dtor 將不會被調用 ,因此,任何人都可以刪除p1
!
因此,當您要使用ctor中new
non-noexcept運算符分配內存時,必須使用RAII包裝器。 C ++ 11或更高版本具有RAII wapper類來分配內存,即std::unique_ptr
或std::shared_ptr
。
順便說一句,
向量不可用
您正在使用什么環境?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.