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?
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 = newint[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; }