c++ - Could this cause a memory leak, returning array from function? -


i have following code works fine except i'm not sure if need delete returned_array pointer in int main() or if automatically deleted. guess not automatically deleted , assume should use delete returned_array; after cout finished. suggestions?

#include <iostream>  double* pass_return_array(double passed[]) {         double* returned_array = new double[3];          for(int index = 0; index < 3; index++)             returned_array[index] = passed[index];          return returned_array; } int main() {         double passed[3];         double* returned_array;          for(int index = 0; index < 3; index++)             passed[index] = index + 100;          returned_array = pass_return_array(passed);          for(int index = 0; index < 3; index++)             std::cout<<returned_array[index]<<std::endl;          return 0; } 

you right: created array in function, responsible deallocation. should call delete[] returned_array; no longer need it.

note, os cleans resources allocated program when terminates, there won't system-wide memory leaks. it's very bad practice leave deallocation os, should deallocate resources allocated (and includes other kinds of things - example handles files or brushes).

consider using std::vector or std::array instead - if used simple local variable, take care of memory allocated , won't have remember it. that's power of c++ in work :)


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -