-1

I have a basic function that creates two-dimensional array and frees it.But when I test my program with leak detector it gives me leakage output.

template <class T1>
T1** 
CreateMatrix(int row ,int col) 
{
  int i;
  T1** matrix;
  matrix = (T1**) malloc(row*sizeof(T1*));
  for (i=0; i<row; i++)
        matrix[i]=(T1*) malloc(col*sizeof(T1));
  return matrix;
}


template <class T1>
void FreeMatrix(int row,T1** matrix) 
{
   int i;
   for (i=0; i<row; i++)
      free(matrix[i]);
   free(matrix);    
}

int** my_matrix=CreateMatrix<int>(3,2);

FreeMatrix<int>(3,my_matrix);
msw
  • 42,753
  • 9
  • 87
  • 112
barp
  • 6,489
  • 9
  • 30
  • 37
  • 1
    Why are you using malloc instead of new? http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new – msw May 15 '14 at 08:20
  • After staring at your code for awhile, I kinda think your leak detector is buggy. – sp2danny May 15 '14 at 08:23
  • 5
    Even better, use class like `std::vector`. – Jarod42 May 15 '14 at 08:23
  • 1
    It would be helpful if you also posted what's the message you're getting from the "leak detector" aka memory profiler. – 101010 May 15 '14 at 08:23
  • After running your code under valgrind, I'm almost positive your leak detector is misreporting a leak. – msw May 15 '14 at 08:35

1 Answers1

1

The provided code (at the time of writing this answer) does not appear to be sufficient to say exactly why you experience a leak, or whether you actually do experience a leak.

If you are interested in that, then please post a complete but minimal example, that readers can compile and try out.

To fix the problem, whatever it is (assuming that it does exist), just use a std::vector for your storage. It takes care of memory management automatically. E.g., off the cuff,

template< class Item >
class Matrix
{
private:
    std::vector<Item>  items_;
    int                width_;

    auto index_of( int x, int y ) const
        -> int
    { return y*width_ + x; }

public:
    auto operator()( int x, int y )
        -> Item&
    { return items_[index_of( x, y )]; }

    auto operator()( int x, int y ) const
        -> Item const&
    { return items_[index_of( x, y )]; }

    Matrix( int w, int h )
        : items_( w*h )
        , width_( w )
    {}
};
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331