【问题标题】:Segmentation Error when using basic_string.h +operator使用 basic_string.h +operator 时出现分段错误
【发布时间】:2013-05-29 04:31:24
【问题描述】:

我有一个简单的代码,基本上如下所示:

static  std::string const part1[] = {"Test1", "Test2", "Test3"};

static  std::string const part2[] = {"Pass", "Fail", "Retry"};

std::string test = part1[1] + part2[0];

我已经包含了string,而basic_string.h 又包含在其中。我知道那里有一个重载的+operator。 当我构建它时,我没有收到任何错误,但是当我尝试运行它时,我收到了分段错误。 我后来注意到的问题是,如果我只是尝试打印数组元素,我会看到相同的分段错误。 我没有看到内存泄漏发生在哪里。有什么线索吗?

【问题讨论】:

  • 什么编译器?我在尝试构建您的代码时遇到了 clang 和 gcc 的语法错误。
  • 对不起,我放这里的时候代码写错了。我将数据声明为: static std::string const part1[] = {"Test1", "Test2", "Test3"};我在 linux 环境中使用 eclipse。

标签: c++ string segmentation-fault


【解决方案1】:

在 C++ 中,数组声明不能以您在代码中使用的方式。

一个有效的代码示例是

static  std::string const part1[] ={"Test1", "Test2", "Test3"};
static  std::string const part2[] = {"Pass", "Fail", "Retry"};

std::string test = part1[1] + part2[0];

【讨论】:

  • 这就是我的代码,对不起,我输入了它而不是复制 pase 等主要类型。我现在注意到的问题是,如果我只是尝试打印数组元素,我会看到分段错误。这意味着我的字符串声明方式不正确?静态 std::string const part1[] = {"Test1", "Test2", "Test3"};
  • 不,我认为声明是正确的。验证您的索引是否存在越界错误
猜你喜欢
  • 2013-11-24
  • 1970-01-01
  • 2017-06-06
  • 2017-08-26
  • 2018-06-18
  • 2019-05-10
  • 2018-02-15
  • 2016-01-15
  • 2011-01-14
相关资源
最近更新 更多