写入阵列时出现分段错误
Segmentation fault when writing to an array
我正在努力创建一个固定大小的空数组,然后写入特定索引。但是,当使用我的 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();
}
肯定在某个地方有初学者的错误吗?
不应该
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
变量,并且在调用测试时类范围的元素变量仍将未定义。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?