In C++, how does a function treat memory that has been dynamically allocated upon exiting the scope of the function? Is this memory cleared, or can it be passed back into the main block?
In context: I have a function, and I pass it a pointer to double to serve as an array. I dynamically allocate this memory within the function, initialise the elements and the exit the function.
void my_func(double* ptr){
ptr = new double[2];
ptr[0] = 15; ptr[1] = 10;
}
In the main block, I then use the newly allocated array.
int main(){
double* ptr;
my_func(ptr);
cout << ptr[0] + ptr[1] << endl;
delete[] ptr;
return 0;
Will this work? Are there dangers/pitfalls associated with this approach?
In C++, memory that has been manually (dynamically) allocated has to be manually deallocated.
You are taking the pointer by value, so while you can change the contents of what the pointer points to you cannot change the pointer itself. Doing so changes only the local copy of the pointer. If you take the pointer by reference, then it would work:
It will mostly work, but its not the way to go in C++ because of the associated pitfalls. Better go with a
vector: