【问题标题】:Stange seg fault when using += with strings将 += 与字符串一起使用时的 Stange 段错误
【发布时间】:2009-05-13 17:21:20
【问题描述】:

在这个 C++ 中一定有一些我没有意识到的明显的东西。

load(string & filename){

 string command;
 char delimiter = '/';
 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);
 command = "import path ";

  //want to add directory to end of command
  string temp = command + "hello!"; // This works
  command.append(directory); //This works!
  command += directory;  //This seg faults!
  ...
}

在 GDB 中,当我在函数开头“打印”文件名时,我得到: (const string &) @0x9505f08: {静态 npos = 4294967295, _M_dataplus = {> = {<:new_allocator> = {}, }, _M_p = 0x950a8e4 "../config/pythonFile.py"}}

这到底是怎么回事,文件名的格式如何不正确,这样 .append() 有效而 += 无效?! C++ 中的重载函数 += 有什么奇怪的吗?

g++ 版本 3.4.6

【问题讨论】:

  • 进入 operator+= 函数以查看它实际崩溃的行。
  • 如果颠倒 append 和 += 的调用顺序会发生什么?还是您一次尝试一个?
  • @harper 死于 += 并且永远不会到达 .append
  • 我试用了你的代码,它就像一个魅力。你用的是哪个编译器?
  • 另外,试试:string temp = "hello";命令 += 温度;这行得通吗?

标签: c++ std


【解决方案1】:

也许这与你在这里如何构建“目录”有关

 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);

rfind 是否以某种方式失败了?如果 rfind 失败,它将返回 here 指定的 std::npos。如果您将 npos 传递给字符串构造函数,我不确定会发生什么行为。它可能取决于平台。

这并不能解释为什么“附加”会起作用而“+=”会崩溃。您可能还存在某种堆损坏(可能是由传递给上面构造函数的 npos 和 C 字符串引起的),并且可能在调用 += 时需要分配新内存。出于任何原因追加可能不需要分配新内存。

无论如何,添加对 npos 的检查是明智的。

【讨论】:

  • 我怀疑你可能是对的,我正在尝试使用 valgrind 追踪内存损坏。
  • 你赢了饼干。库中未正确分配其中一个字符串。 += 在堆外分配的事实显然导致了问题。
【解决方案2】:

我无法重现您的问题。下面的文件在这里与 g++ 一起工作:

#include <string>
#include <iostream>

using namespace std;

int main(int, char**)
{
 string filename("a/b/c/d");

 string command;
 char delimiter = '/';
 size_t delimiterPos = filename.rfind(delimiter);
 string directory = string(filename.c_str(),delimiterPos);
 command = "import path ";

  //want to add directory to end of command
  string temp = command + "hello!"; // This works
  command.append(directory); //This works!
  cout << command << endl;

  command += directory;  //This seg faults!
  cout << command << endl;

}

输出:

$ g++ -o t t.cpp
$ ./t
import path a/b/c
import path a/b/ca/b/c

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2016-04-24
    • 1970-01-01
    相关资源
    最近更新 更多