[英]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
變量就住在初始化函數的范圍,以及變量類范圍的元素仍然是不確定的,當你打電話給你測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.