0

I am attempting to pass a std::vector of a custom class datatype to an function external to the main class. However, I am not sure of the best way to do this. Currently it produces segmentation faults.

Let me explain, I have tried to create a minimum reproducible example below:

I have a class in a header file Poses.h

class Pose
{
  public:
  double x;

  Pose(double x_)
  {
    x = x_;
  }
};

In the main header, lets call it foo.h

#include <vector>
#include "foofcn.h"

class foo{
  public:
  void begin()
  {
  std::vector<Pose> myPoses;
  myPoses[0] = Pose(1);
  myPoses[1] = Pose(2);
  foofcn(myPoses);
  }
};

Where foofcn.h is

#include <vector>
#include "Pose.h"
#include <iostream> 

void foofcn(std::vector<Pose> myFooPoses)
{
  int xx;
  xx = myFooPoses[0].x;
  std::cout << xx << std::endl;
}

This currently produces an error: Segmentation fault (core dumped)

Any help is appreciated

huss987
  • 1
  • 1
  • 5
    The problem is that `myPoses` is empty and you're writing `myPoses[0]` leading to undefined behavior. See dupe: [runtime error: reference binding to null pointer of type 'char'](https://stackoverflow.com/questions/72445084/line-1034-char-9-runtime-error-reference-binding-to-null-pointer-of-type-cha) – Jason Aug 18 '22 at 18:24
  • 1
    Nothing to do with passing vectors, everything to do with how you are initialising the vector in the first place. – john Aug 18 '22 at 18:25
  • Sorry that was a syntax issue on my end. Yes you are correct. – huss987 Aug 18 '22 at 18:26
  • Thank you all. Apologies for dupe. I thought the issue was due to the passing of the vector, not the initialisation. – huss987 Aug 18 '22 at 18:27
  • Look at passing a vector by const reference, or just by reference if you will be manipulating it. – franji1 Aug 18 '22 at 18:28
  • 2
    @huss987 You should *1)* **enable all warnings** and *2)* start using a debugger for your future programs. See [Why should I always enable compiler warnings?](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Aug 18 '22 at 18:29
  • Debug mode of the standard library can also be useful here (`-D_GLIBCXX_DEBUG` for libstdc++, etc), which says at runtime "Error: attempt to subscript container with out-of-bounds index 0, but container only holds 0 elements." (plus extra precisions). – Marc Glisse Aug 18 '22 at 18:33
  • And if your toolchain has sanitizers, you should at the very least use the address and undefined behaviour sanitizers. In GCC and GCC-like tools add `-fsanitize=address,undefined` to the command line. – user4581301 Aug 18 '22 at 18:41

0 Answers0