簡體   English   中英

用string.h將錯誤分割成隊列

[英]segmentation faults with string.h into queue

抱歉,菜鳥問題無法確定在此使用哪些功能。 http://www.cplusplus.com/reference/string/string/

會轉換為C字符串並編寫完整的代碼,但是我敢打賭,這是個好方法。

僅嘗試將A,B和C附加到字符串的末尾並將其添加到隊列中,就不斷出現分段錯誤,它以string :: 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.....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM