写入阵列时出现分段错误

Segmentation fault when writing to an array

本文关键字:分段 错误 阵列      更新时间:2023-10-16

我正在努力创建一个固定大小的空数组,然后写入特定索引。但是,当使用我的 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 变量,并且在调用测试时类范围的元素变量仍将未定义。