Search code examples
c++pointersreturn

What happens to a pointer dereferenced in the return statement?


This is a question related to homework. It is not the homework itself, which I have completed.

Here's part of a function (the only pieces that I think relevant).

double mean(double* pD, int* sz) {
    double *meanPtr = new double;
    *meanPtr = 0.0;
    return *meanPtr; //how to deal with a memory leak in return statement? does it leak?
}

I'm concerned about the last bit. Does this result in a memory leak as I haven't pointed to null or deleted the pointer?


Solution

  • If you need to solve exactly this problem than do like this

    double mean(double* pD, int* sz) {
        double mean = 0.0;
        return mean;
    }
    

    If this is just an example and you need to use pointers, then return a pointer. You can wrap it in std::shared_ptr to prevent manual memory control.