there is a function in it, I allocate memory for array x, perform calculations, then return

double* kramer(double** mat, double* y, int size) { double d = det(mat, size); double* x = new double[size]; for (int i = 0; i < size; i++) x[i] = det(get_mat(mat, y, i, size), size) / d; return x; } 

then in the main program I call the function

 double* p_x = kramer(m, y, s); 

and delete p_x

 delete[]p_x; 

Question: will my memory be freed from under array x, which I allocated in the function?

  • one
    yes, it will be free. - Croessmah
  • Wang, that get_mat () also allocates memory, which is not released ... - Fat-Zer
  • yes, you are right, only here is how to remove it? Create a pointer to this function and then delete it? - Rywes

2 answers 2

The delete and delete[] operators operate on addresses that are passed to them as pointers. The value of the pointer x , obtained through new[] from the function, is returned and assigned to the variable p_x so they store the same address. And that means delete[] work on exactly the address that returned new[] .

For self-checking, you can verify the equivalence of addresses using the debugger. It is clear that before exiting the function, the value of x will need to be stored somewhere, since it will become unavailable in the debugger for direct comparison with p_x .

    It will be free, because you delete array х . p_x is only a pointer to the array x , not a new array

    • thanks a lot - Rywes