So, I have a function which returns a pointer to a dynamically allocated double, and I need to print the value to which it points (silly I know).
double * ans1p = dot(v1, v2);
double ans1 = *ans1p;
cout << "Answer to problem 1:" << endl;
cout << ans1 << endl;
cout << *ans1p << endl;
The first cout statement returns the expected value.
The second returns something random and unexpected. What’s the difference? It seems to be that in both cases what’s being printed is the value pointed to by ans1p.
I’d rather eliminate ans1 and its cout statement entirely.
OK, here is the dot function:
double * dot(Vector &v1, Vector &v2) {
if (getLength(v1) != getLength(v2) ) {
std::cout << "Error: cannot perform dot product. Vectors must be " <<
"equal length." << std::endl;
return 0;
}
double result = 0;
for (unsigned int i = 1; i <= getLength(v1); ++i) {
result += (v1.elements[i] * v2.elements[i]);
}
double * resultPtr = new double;
resultPtr = &result;
return resultPtr;
}
For the record, I wouldn’t attempt to do it this way, but it’s part of an assignment. And I’m supposed to return the 0 pointer in the event of mismatched sizes.
OK, looking at it, I can see that result is out of scope when the function returns, and the pointer I’m returning just points there (right?). But then, I can’t think of how to do what I want to do.
I suppose I could declare a double pointer outside the function, pass the pointer as an argument, and set it inside the function. But I’d kind of like to figure out how to do it the way I planned. Although, thinking about it, it might be better to do it this way once I understand what’s going on with the old way, right?
There’s your problem right there:
You allocate a new
doubleon the heap… then assign the address of a local variable toresultPtr. You get a memory leak (what was allocated withnew doubleis lost), and you then return the address of said local variable. That’s undefined behavior. Which means anything can happen.To fix this, you must change the assignment to actually use the memory you just allocated:
Or, better yet:
Considering the OP has to use a pointer, then this is irrelevant. Left as a bonus (and because I wrote this anyway, deleting it would be a waste).
Or you could also drop the whole memory allocation and return
result.doubles are pretty light, and I really don’t see why you absolutely must return a pointer rather than the value itself: