【问题标题】:Why my C++ program crash in release mode when a struct has default constructors?当结构具有默认构造函数时,为什么我的 C++ 程序在发布模式下崩溃?
【发布时间】:2015-12-11 23:03:33
【问题描述】:

环境: - GNU/Linux(Ubuntu 14.04 和 Mageia 5) - GCC 4.9.2(在 Mageia 下) - 系统 Qt5 和 boost

直到最近,我的程序在调试和发布模式下都没有问题。不相关的更改(并且没有很好地识别)使其崩溃,但仅在发布模式下。不在调试中。

在调试中,valgrind 不会发出任何错误信号。在发布时,它报告使用了未初始化的数据,但在方法的开头。通过系统搜索,我能够追踪到以下结构的使用:

struct LIMA_LINGUISTICANALYSISSTRUCTURE_EXPORT LinguisticElement {
  StringsPoolIndex inflectedForm;
  StringsPoolIndex lemma;
  StringsPoolIndex normalizedForm;
  LinguisticCode properties;
  MorphoSyntacticType type;
  bool operator==(const LinguisticElement& le) const;
  bool operator<(const LinguisticElement& le) const;
};

StringsPoolIndex 和 LinguisticCode 定义为:

BOOST_STRONG_TYPEDEF(uint64_t, StringsPoolIndex);
BOOST_STRONG_TYPEDEF(uint32_t, LinguisticCode);

而 MorphoSyntacticType 是一个枚举。

如果我添加显式构造函数和 operator=,崩溃消失并且 valgrind 停止以指示错误。

LinguisticElement::LinguisticElement() :
  inflectedForm(0),
  lemma(0),
  normalizedForm(0),
  properties(0),
  type(NO_MORPHOSYNTACTICTYPE)

{
}
LinguisticElement::LinguisticElement(const  LinguisticElement& le) :
  inflectedForm(le.inflectedForm),
  lemma(le.lemma),
  normalizedForm(le.normalizedForm),
  properties(le.properties),
  type(le.type)
{
}
LinguisticElement& LinguisticElement::operator=(const LinguisticElement& le)
{
  inflectedForm = le.inflectedForm;
  lemma = le.lemma;
  normalizedForm = le.normalizedForm;
  properties = le.properties;
  type = le.type;
  return *this;
}

我不明白为什么会发生这种情况,因为如果我理解的话,我的实现与编译器生成的实现是一样的。还是我错了?

【问题讨论】:

  • 发布和调试模式在编译器优化方面有所不同。在发布模式下禁用优化,然后重试。
  • 编译器生成的构造函数没有初始化结构成员。

标签: c++ crash


【解决方案1】:

您已将StringsPoolIndexLinguisticCode 定义为固定宽度整数类型。因此,它们不会由编译器合成的构造函数为您的结构初始化。变量通常在调试模式下初始化为空(或某些很少发生的特定值),而在发布模式下不会发生同样的情况,除非明确说明。这就是您仅在发布构建配置中遇到崩溃的原因。

【讨论】:

  • 谢谢。我确信具有内置类型的成员总是在编译器合成的构造函数中初始化为空!我将不得不检查我所有的代码......
猜你喜欢
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 1970-01-01
  • 2012-11-03
  • 2016-10-16
  • 2010-09-24
相关资源
最近更新 更多