Skip to content

freeVector function in Auxiliary.h takes input by value but it should take it by reference #2760

Description

@aasivas

I am copying the function implementation in auxiliary/Auxiliary.h below. This function should take the input by value, otherwise a temporary copy is made, cleared and shrunk, while the original vector is left as is.

template <typename T>
void freeVector(std::vector<T> v) {
  // Give up memory allocated to v.
  // (technically shrink_to_fit does not guarantee to deallocate)
  v.clear();
  v.shrink_to_fit();
}

Here is a small snippet (with slightly modified freeVector) to demonstrate this function does not modify its input

#include <vector>
#include <cstdio>

template <typename T>
void freeVector(std::vector<T> v) {
  // Give up memory allocated to v.
  // (technically shrink_to_fit does not guarantee to deallocate)
  v[0] = 5.;
  printf("v = %g %g %g \n", v[0], v[1], v[2]);
  v.clear();
  v.shrink_to_fit();
}

int main() {
  std::vector<double> a = {1., 2., 3.};
  freeVector(a);
  printf("a = %g %g %g \n", a[0], a[1], a[2]);
  return 0;
}

Fix is as below:

template <typename T>
void freeVector(std::vector<T>& v) {

Let me know if you want to fix this yourself or if you want me to submit an MR. I found this issue after observing some excessive memory usage.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions