1

I created a vector which contains 100 Eigen::Matrix4f. But when I use transforms[i] to access its elements, the programme shows "core dumped: segmentation fault". When I use push_back() function to initialize it, it works well. I checked the size of the vector. It is 100. I am confused about it.

It is in Ubuntu 16.04. I use CMake + GCC to compile it.

Segmentation fault C++ code

std::vector<Eigen::Matrix4f> transforms(100);
//transforms.size() is 100. I checked it.
for(int i = 0; i < transforms.size(); i++)
{
    //I use transforms[i] to access the element in transforms.
    transforms[i] = a_function_returns_a_valid_Matrix4f();
}

The following code works by using std::vector::push_back().

std::vector<Eigen::Matrix4f> transforms;
for(int i = 0; i < 100; i++)
{
    //When I use push_back() to initialize transforms, it works.
    transforms.push_back(a_function_returns_a_valid_Matrix4f());
}

It seems std::vector allocated the memory correctly. I checked its size. But failed to access its element by using transforms[i].

1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
fyl
  • 11
  • 5
  • Is it faster to allocate 100 Matrix4f objects at the beginning of the construction of a std::vector container than using push_back in a loop? – fyl Jun 14 '19 at 19:54
  • 1. Use [at](http://www.cplusplus.com/reference/vector/vector/at/) instead of `[i]`. 2. Can you provide an error log? it's possible that a_function_returns_a_valid_Matrix4f() is causing the segmentation fault. 3. Do you have any other threads in this code that access `transforms`? – SubMachine Jun 14 '19 at 20:49
  • 1
    Please provide a [mcve]! Did you disable assertions (i.e., compiled with `-DNDEBUG`)? Could be a simple alignment issue. If you want to use `.push_back()` you can use `.reserve(100)` at the beginning to avoid re-allocations. – chtz Jun 14 '19 at 21:11
  • @hackela `sizeof(transforms)` is typically `3*sizeof(void*)`, so completely wrong here. `transforms.size()` is correct. – chtz Jun 14 '19 at 21:14
  • 3
    Are you using C++11? Check this out: https://eigen.tuxfamily.org/dox/group__TopicStlContainers.html – mfnx Jun 14 '19 at 23:51

0 Answers0