Evan McNulty
Evan McNulty

Reputation: 3

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?

Upvotes: 0

Views: 2201

Answers (3)

MSalters
MSalters

Reputation: 179779

Assuming that the pointer-part is fixed, you can do this.

double mean(double* pD, int* sz) {
    double *meanPtr = new double;
    *meanPtr = 0.0;
    // Code above is assumed to be a given.
    double result = *meanPtr;
    delete meanPtr
    return result;
}

Modern compilers spot that result is just the name of the return value, and generate efficient code for that. (NRVO, Named Return Value Optimization)

Upvotes: 4

JustAnotherCurious
JustAnotherCurious

Reputation: 2240

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.

Upvotes: 1

user529758
user529758

Reputation:

does it leak?

Of course it does leak like hell.

how to deal with a memory leak in return statement

I can't imagine a scenario when it would be valid to structure your code like this - simply don't do this. Why not just

return 0.0;

or

double foo = 0.0;
return foo;

?

Upvotes: 2

Related Questions