用string.h将错误分段到队列中

segmentation faults with string.h into queue

本文关键字:队列 分段 错误 string      更新时间:2023-10-16

很抱歉,noob问题无法确定在这里使用哪些函数。http://www.cplusplus.com/reference/string/string/

我本来打算转换成c字符串并写一大堆代码,但我敢打赌有一个好方法可以做到这一点。

只需尝试将A、B和C附加到字符串的末尾并将其添加到队列中,就可以不断获得以A结尾的分段错误tho??字符串::assign()后的()函数(根据调试器)

string a, b, c;
a = s.append("A");
b = s.append("B");
c = s.append("C");
q.add(a);
q.add(b);
q.add(c);

这也以分段错误结束。

q.add(s + "A");
q.add(s + "B");
q.add(s + "C");

还有一个问题是它使用了旧的,所以我会得到:

teststringA
teststringAB
teststringABC

而不是预期的

teststringA
teststringB
teststringC

什么是分段错误

当程序运行时,它可以访问内存的某些部分。首先,在每个函数中都有局部变量;这些存储在堆栈中。其次,您可能有一些在运行时分配的内存(在C中使用malloc,或者在C++中使用new)存储在堆上(您也可能听说它被称为"自由存储")。您的程序只允许触摸属于它的内存——前面提到的内存。任何超出该区域的访问都将导致分段故障。分段故障通常被称为分段故障。

你的第二个问题是

q.add(s + "A"); // appends A to s hence teststringA
q.add(s + "B"); // teststringA + B hence teststringAB
q.add(s + "C"); //teststringAB + C hence teststringABC

请参阅http://www.cplusplus.com/reference/string/string/append/

Append to string
The current string content is extended by adding an additional appending string at its end.
The arguments passed to the function determine this appending string:
string& append ( const string& str );
    Appends a copy of str.

示例

// appending to string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
  string str;
  string str2="Writing ";
  string str3="print 10 and then 5 more";
  // used in the same order as described above:
  str.append(str2);                       // "Writing "
  str.append(str3,6,3);                   // "10 "
  str.append("dots are cool",5);          // "dots "
  str.append("here: ");                   // "here: "
  str.append(10,'.');                     // ".........."
  str.append(str3.begin()+8,str3.end());  // " and then 5 more"
  str.append<int>(5,0x2E);                // "....."
  cout << str << endl;
  return 0;
}

输出:

Writing 10 dots here: .......... and then 5 more.....