我正在创建一个固定大小的空数组,然后写入特定索引。但是,使用我的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();
}
当然,这里肯定有一个初学者的错误吗?
尝试编译与'-Wall' ... –
有趣。我用这个输出更新了原始问题。 – Bob
第一个'初学者错误'是你的代码使用指针。 (因为它也会泄漏内存,并且不遵守三项规则。)您可以轻松地从中删除所有指针和“新”。 – Roddy