这是如何产生分段错误的?

时间:2017-05-07 20:52:22

标签: c++ segmentation-fault

每当我尝试将模板化对象推入向量时,我都会收到分段错误。我运行了gdb,仍然无法理解为什么会出现分段错误错误。

Program received signal SIGSEGV, Segmentation fault. 0x0000003f5869d4f3 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::assign(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () from /usr/lib64/libstdc++.so.6

这是我将对象插入向量的地方:

void ReadyDelivery::LoadTruck(){
  string name = "";
  int capacity = 0;
  ifstream inputStream;

  inputStream.open(m_truckFile.c_str());
  while(inputStream >> name >> capacity ){
    Truck<Item, MAX_CAPACITY> t(name,capacity);
    cout<<name<<" "<<capacity<<endl;
    m_truck.push_back(t);
  }

  cout<<"Trucks loaded: "<<m_truck.size()<<endl;
  inputStream.close();

如果我注释掉将对象推入向量的位置,则没有分段错误。

我还有一个返回向量的函数。我不确定这是否会导致它......

vector<Truck<Item,MAX_CAPACITY> > & ReadyDelivery:: GetTruck(){
  return m_truck;
}

感谢您的帮助!

这是m_truck的定义,它是一个私有成员变量:

private:
  vector< Truck<Item, MAX_CAPACITY> > m_truck; //Vector of templated trucks

这是我在模板中构建卡车对象的地方:

template <class T, int N>
  Truck<T,N>::Truck(string inName, int capacity){

  m_name = inName;

  m_capacity = capacity;

}

如果我运行gdb并使用where命令...我得到了这个:

#0  0x000000346ce9d4f3 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::assign(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&) () from /usr/lib64/libstdc++.so.6
#1  0x0000000000402bd9 in Item::operator= (this=0x60eb00) at Item.h:11
#2  0x0000000000402c66 in Tqueue<Item, 200>::~Tqueue (this=0x60e478,
    __in_chrg=<value optimized out>) at Tqueue.h:96
#3  0x0000000000402b43 in Truck<Item, 200>::~Truck (this=0x60e450,
    __in_chrg=<value optimized out>) at Truck.h:114
#4  0x00000000004027d5 in std::_Destroy<Truck<Item, 200> > (__pointer=0x60e450)
    at /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_construct.h:90
#5  0x000000000040249c in std::_Destroy_aux<false>::__destroy<Truck<Item, 200>*>
    (__first=0x60e450, __last=0x60e488)
    at /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_construct.h:100
#6  0x00000000004021d3 in std::_Destroy<Truck<Item, 200>*> (__first=0x60e450,
    __last=0x60e488)
    at /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_construct.h:123
#7  0x0000000000401cdf in std::_Destroy<Truck<Item, 200>*, Truck<Item, 200> > (
    __first=0x60e450, __last=0x60e488)
    at /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_construct.h:149
#8  0x000000000040197c in std::vector<Truck<Item, 200>, std::allocator<Truck<Item, 200> > >::~vector (this=0x7fffffffe1b0, __in_chrg=<value optimized out>)
    at /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:313
#9  0x0000000000401593 in main (argc=1, argv=0x7fffffffe2c8) at driver.cpp:29

0 个答案:

没有答案