Segmentation fault when storing lambda as std::function

Viewed 2002

The following code gives me segmentation fault. After debugging it, I find out that the problem can be solved by declaring the lambda as auto rather than Function. Why is that the case?

#include <functional>
#include <iostream>
#include <vector>

typedef std::vector<double> Vec;
typedef std::function<const Vec&(Vec)> Function;


int main()
{
     //Function func = [](const Vec& a)->Vec /*this give me segfault*/
     auto func = [](const Vec& a)->Vec /*this work just fine??*/
         {
              Vec b(2);
              b[0] = a[0] + a[1];
              b[1] = a[0] - a[0];
              return b;
         };
     Vec b = func(Vec{1,2});
     std::cout << b[0] << " " << b[1] << "\n";
     return 0;
}

It would be great if I can declare it as Function because I would like to pass this lambda expression to some other classes.

The error that I have when func is declared as Function is:

Program received signal SIGSEGV, Segmentation fault. 0x0000000000401896 in std::vector >::size (this=0x0) at /usr/include/c++/5/bits/stl_vector.h:655 655 { return size_type(this->_M_impl._M_finish - this->_M_impl._M_start); }
(gdb) backtrace
#0 0x0000000000401896 in std::vector >::size (this=0x0) at /usr/include/c++/5/bits/stl_vector.h:655
#1 0x00000000004015aa in std::vector >::vector (this=0x7fffffffdc50, __x=) at /usr/include/c++/5/bits/stl_vector.h:320
#2 0x0000000000400d12 in main () at test.cxx:18

2 Answers
Related