Home > other >  Memory leak caused by array of pointers?
Memory leak caused by array of pointers?

Time:03-09

I'm making chess in c , by making an array of pointers to class Piece.

Piece* chessboard[8][8];
Piece pieces[32];

Each chessboard field that has a piece points to an element of array pieces[] and those that don't have a piece, point to NULL. Here's a fragment of chessboard initialization function:

    for (int i = 0; i < 8; i  )
    {
        for (int j = 0; j < 8; j  )
        {
            chessboard[i][j]=NULL;
            if(i==6)
                isBlack=0;
            if(i==0 || i==7)
            {
                switch(j)
                {
                    case 0:
                    case 7: chessboard[i][j]=&pieces[tmp];
                            pieces[tmp  ].setPiece(isBlack,rook);
                            break;

Class Piece has only an enumerator and fundamental type variables:

enum Figure
{
    king,queen,rook,bishop,knight,pawn
};
class Piece
{
    bool isBlack;
    Figure figure_type;
    public:
    Piece() {};

If a piece hits another piece, the pointer is simply overwritten like so:

chessboard[7-(y2-'1')][x2-'a'] = chessboard[7-(y1-'1')][x1-'a'];
chessboard[7-(y1-'1')][x1-'a'] = NULL;

Does this cause a memory leak? I think not, because array pieces[] keeps track of all the pointers, but my paranoia gets better of me. Would it cause memory leaks if class Piece had some constructed classes, i.e.

class Piece
{
    bool isBlack;
    std::vector<std::string> figure_type;
    public:
    Piece() {};

?

CodePudding user response:

Piece pieces[32];

chessboard[i][j]=&pieces[tmp];

chessboard[7-(y2-'1')][x2-'a'] = chessboard[7-(y1-'1')][x1-'a'];
chessboard[7-(y1-'1')][x1-'a'] = NULL;

Does this cause a memory leak?

No. This does not cause a memory leak.

Memory leaks when you allocate dynamic memory, and lose the pointer to that dynamic memory so that the dynamic memory cannot be freed anymore. The shown program doesn't allocate any dynamic memory (except through the vector member, but the vector class takes care to not leak the memory that it manages).

  • Related