Niteya Shah
Niteya Shah

Reputation: 1824

How to stop this memory leak

I am learning pointers in C++ and am working on the new and delete functionality . I have a local function which allocates memory on the heap but because i am returning the 2d array that i have created , I dont understand how to plug this memory leak, any help would be appreciated

main.cpp

#include<iostream>
#include "integers.h"
using namespace std;
int main()
{
int i[]={1,2,3,4};
int n=sizeof(i)/sizeof(int);
cout<<n<<endl;
printint(genarr(i,n),n);
}

integers.cpp

#include<iostream>
using namespace std;
int** genarr(int* val,int n)
{
int i,j;
int **a=new int*[n];
for(i=0;i<n;i++)
a[i]=new int[n];

for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(i==j)
a[i][j]=val[i];

return a; // The variable that will leak but because i am returning it , how do stop it
}

void printint(int** a,int n){
for(int i=0;i<n;i++)
 {
  for(int j=0;j<n;j++)
   {
    cout<<a[i][j]<<" ";
   }
cout<<endl;
}
return ;
}

integers.h

int** genarr(int*val, int n);
void printint(int **a,int n);

compiled by

g++ main.cpp integers.cpp -o integers

I have heard about smart pointers and am planning to learn about them after this , but for now i want to know if there is way to fix this or should i just go for smart pointers ?

Upvotes: 1

Views: 81

Answers (2)

melpomene
melpomene

Reputation: 85897

To fix the problem, you need to delete what you new'd.

Change the code in main to:

int **arr = genarr(i,n);
printint(arr,n);
// we're done using arr; now we need to free it
for(int j=0;j<n;j++)
    delete[] arr[j];
delete[] arr;

You can also extend integers.cpp and add a delarr function that complements genarr:

void delarr(int **a, int n) {
    for (int i = 0; i < n; i++) {
        delete[] a[i];
    }
    delete[] a;
}

Then main becomes simply:

int **arr = genarr(i,n);
printint(arr,n);
delarr(arr,n);

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249642

The easiest way to avoid memory leaks in C++ is to avoid explicitly calling delete anywhere. Smart pointers can solve this for you.

In your specific case, you could try something like this (untested):

using Vector = unique_ptr<int[]>;
using Matrix = unique_ptr<Vector[]>;

Matrix genarr(const int* val, int n)
{
    Matrix a(new Vector[n]);
    for(int i=0;i<n;i++)
        a[i].reset(new int[n]);

    // ...

Upvotes: 3

Related Questions