0

I am trying to return an array of doubles. When my function returns it, and then I try to read from it in int main it is telling me the value is 0.

We see this in the screenshot below.

My minimal verifiable example is:

#include <iostream>
#include <stdlib.h>
#include <vector>

using namespace std;

double* pi_sequence(const int& len)
{
  vector<double> ests(len);
  double first = 3.123;
  ests[0] = first;
  cout << "first " << first << " ests.at:" << ests.at(0) << endl;
  return ests.data();
}

int main() {
  double* ests = pi_sequence(1);
  std::cout << "after returned: " << ests[0]  << std::endl;
}

Can you please help me understand why it is 0 after the return, and why it doesn't stay.

enter image description here

Kyefus
  • 546
  • 5
  • 5
  • 2
    Possible duplicate of [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Retired Ninja Jan 17 '19 at 00:46

2 Answers2

2

Upon exiting pi_sequence function, vector<double> ests is destroyed.

Since data() returns a pointer to the underlying array then it points to invalid memory when returning to the caller, since that memory is released by vector<T> destructor.

Why don't you just return the vector itself by value? It will be optimized by RVO (or move semantics) in any case so you won't get much difference.

Jack
  • 131,802
  • 30
  • 241
  • 343
1

You are returning a pointer to something that no longer exists. Since the vector is local to the function, it no longer exists when the function returns. So a pointer to the objects that were in the vector is now a pointer to whatever junk, if anything, happens to be stored where the vector was before.

Think about it -- what double do you think you're printing? No doubles exist at that point in the code. If you're thinking "the first double in the vector", ask yourself what vector. The ests vector is out of scope and if you called pi_sequence again, a new one would be created.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • If I put `static ests` inside the `pi_sequence` function, then i seem to be able to access right? Does `static` make it get allocated on heap? And I have to manually clear it up doing `delete returnedEsts`? – Noitidart Jan 17 '19 at 01:38
  • 1
    If you use `static`, there will be one and only one such vector and it will exist for at least `main` and any function called from it. You *can't* `delete` it if its `static`. The `delete` function is part of C++'s dynamic allocation and a static object can't be deleted on demand or it wouldn't be static. – David Schwartz Jan 17 '19 at 03:14