我已经通过我的很多类(class)跟踪了这个问题,令我惊讶的是,这个错误的根源是一个简单的 std::string = std::string
操作。
我不会发布整个代码,只发布按顺序执行的功能。我仍然认为 SO 标准的代码太多,但我看不到其他选择。
一些上下文注释:
- OrderedPair 是单独的
lib.inc
文件中的公共(public)结构{ int y, int x }
。 - 前导下划线标记函数头中声明的变量
- 末尾下划线标记类成员变量
ncefm.cc -- 基本上是主文件
std::vector<std::string> juststring = {"teststring", "another string", "foobar"};
List* list0 = new List(w0_, juststring); // Source of the error
list.cc -- 构造函数 List()
在这里被调用
忽略可选变量,它们无论如何都不会被调用
List::List(Frame* const _parent, std::vector<std::string> &_list,
const OrderedPair &_pos = {0, 0}, const unsigned int &_spacing = 1,
const unsigned int &_maxsize = 0) {
pos_ = _pos;
size_ = _list.size();
spacing_ = _spacing;
maxsize_ = _maxsize;
parent_ = _parent;
Fill(_list); //Source of the error
Redraw();
parent_->AddWidget(this);
}
list.cc -- 成员函数Fill()
list_ 是 std::vector 类型的成员变量
void List::Fill(std::vector<std::string> &_list) {
for (unsigned int loop = size_; loop < (size_ + _list.size()); loop++) {
list_.push_back(new Label(parent_, _list[loop], {pos_.y + (loop * spacing_),
pos_.x}, maxsize_)); // source of the error (the constructor Label() )
}
}
label.cc -- 构造函数 Label() 在这里被调用
Label::Label(Frame* const _parent, std::string &_text,
const OrderedPair &_pos = {0,0}, const unsigned int &_maxsize = 0) {
pos_ = _pos;
maxsize_ = _maxsize;
parent_ = _parent;
SetText(_text); // Source of the error
parent_->AddWidget(this);
}
list.cc -- 成员函数SetText()
我们终于到了,错误的来源是......
void Label::SetText(std::string& _text) {
if (maxsize_ != 0 && _text.length() > maxsize_) _text.resize(maxsize_);
text_ = _text; // THIS?!
size_ = text_.length();
Redraw();
}
如果我只是注释掉这一行,错误就会消失, 当然,这会破坏功能。 text_.assign(_text);也不起作用。
label.h -- 显示头文件和一些变量的定义 text_
class Label {
private:
OrderedPair pos_;
unsigned int size_;
unsigned int maxsize_;
std::string text_;
Frame* parent_;
public:
Label(Frame* const _parent, std::string &_text, const OrderedPair &_pos,
const unsigned int &_maxsize);
~Label();
inline const Frame* GetParent();
inline unsigned int GetSize();
inline std::string Text();
void SetText(std::string&);
void Move(const OrderedPair &_pos);
void RMove(const OrderedPair &_pos);
void Redraw();
void Clear();
};
如果这太乱了,或者您认为您需要有关我的类(class)的更多信息,请让我在这里添加它们,或者查看我在开发分支上的 GitHub 存储库(公共(public))here .
最佳答案
for (unsigned int loop = size_; loop < (size_ + _list.size()); loop++)
{
[...] _list[loop] [...]
}
您在列表构造函数中将 size_
设置为 _list.size()
,这意味着您从末尾开始迭代列表,并且 _list[loop ]
超出范围。
你不是这个意思吗?
for (unsigned int loop = 0 ; loop < _list.size() ; loop++)
{
[...] _list[loop] [...]
}
关于c++ - 导致段错误的简单字符串分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41219293/