1

I am trying to return a pointer to std::vector from a function as follows:

std::vector<int>* find_solution(const std::vector<int>& list)

I tried the following solutions:

const std::vector<int>* find_solution(const std::vector<int>& list)

and

vector<int>* find_solution(const std::vector<int>& list)
{
    //populate solution_list
    std::vector<int>* return_list = new std::vector<int>;
    return_list = &solution_list;
}

where solution_list is the name of the local vector I would like to return a pointer to. Neither of them worked, the returned vector is always empty. Any tips would be greatly appreciated, but keep in mind that the program calling this function needs to be able to manage the vector in memory. In other words, returning the vector object is not a viable solution. Thanks!

Swordfish
  • 12,971
  • 3
  • 21
  • 43
software_guy
  • 33
  • 1
  • 4
  • 4
    "*the local vector I would like to return a pointer to*" - You can't return a pointer to a local variable. Local variables are destroyed when the function returns. – melpomene Oct 20 '18 at 16:50
  • 3
    "but keep in mind that the program calling this function needs to be able to manage the vector in memory. In other words, returning the vector object is not a viable solution." ***Why?*** – Swordfish Oct 20 '18 at 16:51
  • 2
    `return_list = new ...; return_list = ...` is a memory leak. – melpomene Oct 20 '18 at 16:53
  • Not if I delete the pointer later in my code right? – software_guy Oct 20 '18 at 16:57
  • 1
    You've just lost the only pointer to the memory `new` allocated. How are you going to delete it later? – melpomene Oct 20 '18 at 16:58
  • A std::vector is not recursive. There are no std::vector's in side of one. – 2785528 Oct 20 '18 at 22:02

1 Answers1

2
vector<int>* find_solution(const std::vector<int>& list)
{
    //populate solution_list
    std::vector<int>* return_list = new std::vector<int>;
    return_list = &solution_list;
}

You have to use the allocated vector:

vector<int>* find_solution(const std::vector<int>& list)
{
    std::vector<int>* solution_list = new std::vector<int>;

    //populate solution_list

    return solution_list;
}

When you return_list = &solution_list; you overwrite the only pointer to the allocated memory so it can never be deallocated. Also, you would return the address of a local variable that is gone when the function ends.

But you shouldn't have to allocate a std::vector<int> dynamically to begin with since it consists only of a few size_ts and a pointer to the data. Just:

vector<int> find_solution(const std::vector<int>& list)
{
    std::vector<int> solution_list;

    //populate solution_list

    return solution_list;
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43