delete heap after returning pointer

Hi all,

I have a function as follow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int* readFile(string InputPath)
{
    int *myvar = new int[10]; //The file has 10 lines (Using heap)

    ifstream inFile;

    inFile.open(InputPath.c_str(), ios::in);

    if (inFile.fail())
    {
        cout << "Error reading the input file ";
        cout << InputPath << ".";
        exit(0);
    }
    string fileLine;

    while (getline(inFile, fileLine))
    {
       myvar[i]=toint(fileLine); //will be converted to int!
    }
    ;
    inFile.close();
    

        
    return myvar;
}


How can I free the heap (myvar)?
In general, what is the best method to return such array?
Last edited on
How can I free the heap (myvar)?


The int* you return; don't change it, don't lose it, and when you're done with the memory,

delete [] theReturnedPointer;

Unless you've got a really good reason for making it an array, you could save yourself the bother of memory management and just use a vector.
Last edited on
first,i do not suggest write like this.
i usually write like this
void readfile(string InputPath,char* ReturnedPointer)
{
...
return ;
}
and the ReturnedPointer to be dealed outside of the function.
what is the best method to return such array?

The best method is to return a vector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
vector<int> readFile(const string& InputPath)
{
    ifstream inFile(InputPath); // or inputPath.c_str() for old compilers
    if (!inFile)
    {
        cout << "Error reading the input file " << InputPath << ".";
        exit(0); // thow would be better! Or at least return an empty vector.
    }

    vector<int> myvar;
    for(int n; inFile >> n && myvar.size() < 10; )
    {
       myvar.push_back(n);
    }
    return myvar;
}


But if you really really want to use new[], then at least return the self-managing pointer, std::unique_ptr<int[]>. Never let a raw pointer escape a function, not in C++.
Last edited on
How can I free the heap (myvar)?


The int* you return; don't change it, don't lose it, and when you're done with the memory,

delete [] theReturnedPointer;

Unless you've got a really good reason for making it an array, you could save yourself the bother of memory management and just use a vector.


So, myvar pointer can be easily deleted in my main program by adding delete[] theReturnedPointer.

if so,


But if you really really want to use new[], then at least return the self-managing pointer, std::unique_ptr<int[]>. Never let a raw pointer escape a function, not in C++.



What is the problem with previous code (delete[] theReturnedPointer)?

Does the compiler realise the heap correctly and delete it without any problem?
Last edited on
What is the problem with previous code (delete[] theReturnedPointer)?

Two problems:1) it is exception-unsafe 2) it is difficult to maintain if your program is larger than a few lines.
3) the caller doesn't know how large the array is
The tutorial seems fine.

What's the similarity between what you've done and the tutorial?
We are both using new inside function and are going to use delete outside function.
I see. The examples are not exception safe. So yes, they're incorrect in that respect. But they are illustrating how to construct multi-dimension arrays, so you have to take what you can from the them.

Your real problem is one of design that happens to have technical problems too. Like I said, there's no way know the size of the array being passed back from you function. No one can use an array unless the size is known, for all the caller knows the size could be zero.

Last edited on
So, in addition of sending an array, the size of array in all dimensions must be send as well, and using delete just have exception problem, and will not cause memory leakage after deleting heap outside the function.
Last edited on
So, in addition of sending an array, the size of array in all dimensions must be send as well
You need to think about how someone might use your function. If they just get a pointer, how will they how to treat it?

and using delete just have exception problem, and will not cause memory leakage after deleting heap outside the function
I'm not sure what you mean, but the delete must match the allocation.
Thank you for your the answers.

and using delete just have exception problem, and will not cause memory leakage after deleting heap outside the function
I'm not sure what you mean, but the delete must match the allocation.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
template <typename T> 
T **AllocateDynamicArray( int nRows, int nCols)
{
      T **dynamicArray;

      dynamicArray = new T*[nRows];
      for( int i = 0 ; i < nRows ; i++ )
      dynamicArray[i] = new T [nCols];

      return dynamicArray;
}

template <typename T>
void FreeDynamicArray(T** dArray)
{
     for( int i = 0 ; i < ROWS ; i++ ) //line 16
         delete [] dArray[i] ;
     delete [] dArray;
}

int main()
{
      int **my2dArr = AllocateDynamicArray<int>(4,4); //Line 23
      my2dArr[0][0]=5;
      my2dArr[2][2]=8;
      cout << my2dArr[0][0] << my2dArr[0][1] << endl;
      cout << my2dArr[1][1] <<  my2dArr[2][2]<< endl;
  
      FreeDynamicArray<int>(my2dArr); //Line 29
      return 0;
}


In line 16-18 a function has been defined to delete the heap. Is it safe to use this function in line 29 to delete the allocated memory in line 23.
Last edited on
Yes.
Thanks a lot.
^Actually, you probably want to pass in a parameter to the FreeDynamicArray function so it can actually delete the correct number of rows. Right now, it's deleting ROW loops which may be different than the number you have allocated with AllocateDynamicArray.
Topic archived. No new replies allowed.