Clear memory before return

Apr 25, 2019 at 11:58pm
If I have a function that creates allocates a memory dynamically in it, before returning a value should I free the memory or I can just return and it will free up the memory automatically?

1
2
3
4
5
6
7
8
9
10
11
bool finder(){
    int* arr = new int[20];
    fillArray(arr);
    .
    .
    .
    delete[] arr;
    return true;

}
Last edited on Apr 25, 2019 at 11:58pm
Apr 26, 2019 at 1:50am
At end all dynamically allocated memory should get freed. If the memory was allocated manually, then it should also get freed manually. For avoiding fiddling with that, it would be at best, if all memory allocation happens at class constructor and the deallocation at the destructor.
Consider the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
int * arr = new int[2000];
...
try {
    for( int i = 0; i < 20000; ++i)
    {
        if ( i < 0 || i >= 2000) throw out_of_range( "At my_fnc: wrong index!");
        arr[i] = i + i % 0x10;
        ...
    }
    ...
    delete[] arr;
}
catch ( exception & e) { std::cerr << e.what(); throw; }

See you what''s wrong?
Topic archived. No new replies allowed.