2014-02-08 38 views
0

我正在创建一个固定大小的空数组,然后写入特定索引。但是,使用我的pushFront()方法执行此操作时,我收到了分段错误。写入数组时分段错误

用gdb看代码后:

(gdb) list 
337   * first element in the %vector. Iteration is done in ordinary 
338   * element order. 
339   */ 
340   const_iterator 
341   begin() const 
342   { return const_iterator (this->_M_impl._M_start); } 
343 
344   /** 
345   * Returns a read/write iterator that points one past the last 
346   * element in the %vector. Iteration is done in ordinary 

编译与-Wall:

file.cpp: In constructor ‘StringStuff::StringStuff(int)’: 
file.cpp:18:20: warning: unused variable ‘elements’ [-Wunused-variable] 
    vector<string>* elements = new vector<string>(2*guaranteedCapacity); 

这我不知道做什么。我的代码如下,我基本上调用了一个测试函数,它试图将字符串“test”添加到数组中。

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 

class StringStuff{ 
    vector<string>* elements; 
    int frontItem; 
    int rearSpace; 
    int upperBound; 

    public:    
     StringStuff(int guaranteedCapacity) { 
      vector<string>* elements = new vector<string>(2*guaranteedCapacity); 
      frontItem = guaranteedCapacity; 
      rearSpace = guaranteedCapacity; 
      upperBound = 2 * guaranteedCapacity; 
     } 

     virtual void pushFront(string newItem){ 
      elements->at(--frontItem) = newItem; 
     } 
     virtual void test01(){  
      pushFront("test"); 
     } 
}; 

/** Driver 
*/ 
int main() { 
    StringStuff* sd = new StringStuff(100); 
    sd->test01(); 
} 

当然,这里肯定有一个初学者的错误吗?

+0

尝试编译与'-Wall' ... –

+0

有趣。我用这个输出更新了原始问题。 – Bob

+1

第一个'初学者错误'是你的代码使用指针。 (因为它也会泄漏内存,并且不遵守三项规则。)您可以轻松地从中删除所有指针和“新”。 – Roddy

回答

1

不应该

virtual void pushFront(string newItem){ 
    newItem = elements->at(--frontItem); 
} 

virtual void pushFront(string newItem){ 
    elements->at(--frontItem) = newItem; 
} 

而且,看着提示-Wall为您提供:

vector<string>* elements = new ... 

应该只是

elements = new ... 

或将定义另一个elements变量就住在初始化函数的范围,当你调用你的测试时,类范围元素变量仍然是未定义的。

+0

它会抛出分段错误。 我有这个倒退吗?不是将“测试”添加到数组中,而是将--frontItem中的元素分配给一个变量newItem? – Bob

+0

那么,你的OP说“试图将字符串”测试“添加到数组中。” –

+0

是的,这就是我想要做的,我相信目前的代码是正确的? – Bob