2016-12-24 78 views
1

所以我製作了一個模擬井字遊戲的程序,並用valgrind運行它,它說我有內存泄漏。什麼是造成這種泄漏,我該如何解決?如何修復我的程序的這個小內存泄漏?

這裏是從Valgrind的輸出:

==15253== 
==15253== HEAP SUMMARY: 
==15253==  in use at exit: 72,704 bytes in 1 blocks 
==15253== total heap usage: 37 allocs, 36 frees, 76,864 bytes allocated 
==15253== 
==15253== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1 
==15253== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==15253== by 0x4EC5B1F: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.22) 
==15253== by 0x40104E9: call_init.part.0 (dl-init.c:72) 
==15253== by 0x40105FA: call_init (dl-init.c:30) 
==15253== by 0x40105FA: _dl_init (dl-init.c:120) 
==15253== by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so) 
==15253== 
==15253== LEAK SUMMARY: 
==15253== definitely lost: 0 bytes in 0 blocks 
==15253== indirectly lost: 0 bytes in 0 blocks 
==15253==  possibly lost: 0 bytes in 0 blocks 
==15253== still reachable: 72,704 bytes in 1 blocks 
==15253==   suppressed: 0 bytes in 0 blocks 
==15253== 
==15253== For counts of detected and suppressed errors, rerun with: -v 
==15253== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0) 

這裏是代碼:

main.cpp中:

#include <iostream> 
#include "../include/Board.h" 

using namespace std; 

/** 
* Main function that is run. 
* @return: 0 on exit success 
*/ 
int main() { 
    Board b; 
    int r, c; 
    int moveCount = 0; 

    cout << "* * * * * Welcome to the Tic-Tac-Toe game! * * * * *" << endl; 
    cout << "Enter numbers 1, 2, or 3 when prompted for coordinates of your move." << endl; 
    cout << b.toString() << endl; 

    // Loops until there are no more possible moves. 
    while(moveCount < 9) { 
     // Prompts for coordinates to make a move. 
     do { 
      if(moveCount % 2 == 0) { 
       cout << "Player X's turn, enter the row and column of your move.\nRow #:"; 
      } 
      else { 
       cout << "Player O's turn, enter the row and column of your move.\nRow #:"; 
      } 
      cin >> r; 
      cout << "Column #:"; 
      cin >> c; 

      // Checks if the move is valid. 
      if(b.canPut((r - 1), (c - 1)) != 1) { 
       cout << "\nInvalid move, re-enter the desired coordinates.\n" << endl; 
      } 
     }while(b.canPut((r - 1), (c - 1)) != 1); 

     // Makes the move. 
     if(moveCount % 2 == 0) { 
      b.makeMove((r - 1), (c - 1), X); 
     } 
     else { 
      b.makeMove((r - 1), (c - 1), O); 
     } 

     cout << b.toString() << endl; 

     // Checks if there is a winner and breaks the loop if there is. 
     if(b.checkWinner() != 0) 
      break; 
     moveCount++; 
    } 

    // Prints the appropriate statement base on the winning status, if any. 
    if(moveCount == 9) { 
     cout << "\nGame over, stalemate." << endl; 
    } 
    else { 
     if(b.checkWinner() == X) { 
      cout << "\nPlayer X has won!!!" << endl; 
     } 
     else if(b.checkWinner() == O) { 
      cout << "\nPlayer O has won!!!" << endl; 
     } 
    } 

    return 0; 
} 

Board.h:

#ifndef BOARD_H 
#define BOARD_H 

#include <string> 
#define X 1 
#define O 5 
#define SIZE 3 

/** 
* Board class for tic-tac-toe project. 
*/ 
class Board { 
    private: 
     int **grid; 
    public: 
     Board(); 
     ~Board(); 
     int checkWinner(); 
     int canPut(int r, int c); 
     void makeMove(int r, int c, int val); 
     std::string toString(); 
}; 

#endif 

Board.cpp:

#include "../include/Board.h" 
#include <string> 

using namespace std; 

/** 
* Constructor for a Board object. 
*/ 
Board::Board() { 
    grid = new int*[SIZE]; 

    // Creates all the 1D arrays to make the 2D array. 
    for(int ctr = 0; ctr < SIZE; ctr++) { 
     grid[ctr] = new int[SIZE]; 
     for(int i = 0; i < SIZE; i++) { 
      grid[ctr][i] = 0; 
     } 
    } 
} 

/** 
* Destructor for a Board object. 
*/ 
Board::~Board() { 
    for(int ctr = 0; ctr < SIZE; ctr++) { 
     delete[] grid[ctr]; 
    } 
    delete[] grid; 
} 

/** 
* Checks if there is a winner for the current game. 
* @return: 0 if no winner, X if X player wins or O if O player wins 
*/ 
int Board::checkWinner() { 
    int sum; 

    // Checks all the rows for a winner. 
    for(int i = 0; i < SIZE; i++) { 
     sum = 0; 
     for(int ctr = 0; ctr < SIZE; ctr++) { 
      sum += grid[i][ctr]; 
     } 
     if(sum == 3) { 
      return X; 
     } 
     else if(sum == 15) { 
      return O; 
     } 
    } 

    // Checks all the columns for a winner. 
    for(int a = 0; a < SIZE; a++) { 
     sum = 0; 
     for(int b = 0; b < SIZE; b++) { 
      sum += grid[b][a]; 
     } 
     if(sum == 3) { 
      return X; 
     } 
     else if(sum == 15) { 
      return O; 
     } 
    } 

    // Checks the top-left to bottom-right diagonal for a winner. 
    sum = 0; 
    for(int i = 0; i < SIZE; i++) { 
     sum += grid[i][i]; 
    } 
    if(sum == 3) { 
     return X; 
    } 
    else if(sum == 15) { 
     return O; 
    } 

    // Checks the top-right to bottom-left diagonal for a winner. 
    sum = 0; 
    for(int r = 0, c = SIZE - 1; r < SIZE && c > 0; r++, c--) { 
     sum += grid[r][c]; 
    } 
    if(sum == 3) { 
     return X; 
    } 
    else if(sum == 15) { 
     return O; 
    } 

    // Returns zero because after checking all the possibilities, a winner has not been found. 
    return 0; 
} 

/** 
* Determines if there is an open spot on the board at the given coordinates. 
* @param r: the row to be checked 
* @param c: the column to be checked 
* @return: 1 if there is an open spot, 0 if not 
*/ 
int Board::canPut(int r, int c) { 
    if(grid[r][c] == 0) 
     return 1; 
    return 0; 
} 

/** 
* Simulates making a move for a player. 
* @param r: the row to set the value 
* @param c: the column to set the value 
* @param val: the value to be set at the given coordinates 
*/ 
void Board::makeMove(int r, int c, int val) { 
    grid[r][c] = val; 
} 

/** 
* Creates a representation of the board as a string. 
* @return: string of the board 
*/ 
string Board::toString() { 
    char a, b, c; 
    string output = "Board:\n"; 

    // Loops through every line for the 2D array. 
    for(int ctr = 0; ctr < SIZE; ctr++) { 

     // Loops through every value of the 1D array being checked. 
     for(int i = 0; i < SIZE; i++) { 
      output += ' '; 
      if(grid[ctr][i] == X) { 
       output += 'X'; 
      } 
      else if(grid[ctr][i] == O) { 
       output += 'O'; 
      } 
      else { 
       output += ' '; 
      } 
      if(i != (SIZE - 1)) { 
       output.append(" |"); 
      } 
      else { 
       output += '\n'; 
      } 
     } 

     // Pads each line with a line of '-' characters. 
     if(ctr != (SIZE - 1)) { 
      for(int i = 0; i < (SIZE * 4) - 1; i++) { 
       output += '-'; 
      } 
      output += '\n'; 
     } 
    } 
    return output; 
} 

回答

2

因此,那個內存泄漏不是你的問題。這是程序在執行初始化之前發生的內存泄漏,甚至在執行任何代碼之前。

Valgrind通常忽略這些。它有一個文件,其中列出了需要在各種平臺上的各種庫中忽略的內容。也許你使用了一個Valgrind選項,告訴它不要忽略它們,或者它可能沒有被正確設置爲該平臺上libstdC++的確切版本。

作爲一個不相關的C++風格的筆記,我會說我不是很喜歡你使用#defineBoard.h。你應該聲明const

+0

謝謝您的信息。爲什麼你說我不應該在Board.h中使用'#define'?我是C++的新手,所以我不習慣這種語言的通用約定。 –

+0

@AnthonyPalumbo - 預處理器是......好,被認爲是醜陋的。將它用於'#include'和(如果絕對必要)條件編譯('#if'和'#ifdef'等)。使用'#define'很醜,因爲它完全踐踏了作用域規則和類型規則以及其他各種事情。 C++具有內聯函數。你可以說像'const int foo = 5;'而不是'#define foo 5'這樣的東西,'foo'現在有一個類型,並且被視爲一個具有範圍的正確標識符。爲什麼要避免預處理器實際上很複雜。 – Omnifarious

2

你的代碼看起來不錯,但我建議不要使用網格指針指針,這有點棘手。 而不是int **grid, 有int grid[SIZE][SIZE]。 然後你不需要任何新的和刪除調用 - 沒有內存泄漏的源! 這工作,除非SIZE非常大,你嘗試在堆棧上分配板。如果SIZE很大,只需在堆上分配板卡b = new Board()即可。 (不要忘記刪除它!)