簡體   English   中英

2D陣列中的內存泄漏

[英]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
}

我怎么想我的程序應該工作:

  1. 默認構造函數被調用,不需要自定義的。
  2. 檢查輸入是否滿足要求。 如果不是 ,則返回false從而完成程序。 內存尚未動態分配(停留在nullptr ),沒有問題。
  3. 如果是,請使用calloc 創建2D數組 (我知道我正在將C與C ++混合使用,想使用class和vector不可用)。
  4. 用掃描值填充該2D數組。 如果掃描的值不是整數,則返回false,從而完成程序。
  5. 打印該數組的值。 const函數。
  6. 完成程序,以便調用析構函數。 由於我不知道Create()是否提前結束(在calloc之前),因此我默認將int **map初始化為nullptr 如果我分配了, map將不再是nullptr ,將需要釋放。 否則,析構函數應該free ,這就是Clean()所做的。
  7. Clean()我遵循動態分配和釋放的做法。 callocfree遵循相反的模式。 調試確認已調用了多少calloc已調用了許多free

有了所有這些, valgrind仍然會報告錯誤(無法reachable ,實際錯誤)。 具體來說: total heap usage: 184 allocs, 23 frees 是什么導致了此錯誤,我錯過了什么?

編輯:初始化的rowscolumns成員。 使用C ++ newdelete更改了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_ptrstd::shared_ptr

順便說一句,

向量不可用

您正在使用什么環境?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM