簡體   English   中英

如何解釋GDB回溯以確定分段錯誤?

[英]How to interpret a GDB backtrace in order to determine a segmentation fault?

我在入門級編程課程中。 我知道分段錯誤是由於在此過程中某處的內存存儲錯誤所致。 我編寫的程序應該采用一個給我們的文件,該文件已包含在代碼中,並且包含將其解碼然后打印解碼后的消息的指令。

我們有幾個測試用例,我的代碼針對其中一些運行,但沒有針對最后一個。 今天,我第一次學習了有關GDB的調試信息,並使用完整的backtrace嘗試查找錯誤源,但是我不確定如何解釋它給我的含義。

這是我編寫的代碼。 **編輯后的代碼

當我進行回溯時,這就是告訴我的。

   #2  0x0000000000401523 in main () at main.cpp:42
    second = 61 '='
    third = 72 'H'
    msg = 0x606308
    i = 8
    chars = ""
    first = 90 'Z'
    numMess = 8
    out = <incomplete type>
    name = "input4.txt"
    in = <incomplete type>
    arr = "IJKLMNOPQRSTUVWXYZABCDEFGH"

我不知道回溯在告訴我什么,我不確定如何處理這些信息以發現並修復我的錯誤。

痕跡的提示是

i = 8
chars = ""
numMess = 8

i等於numMess並且chars為空。

為什么這么重要? 查看numMess來源,我們看到它用於確定由msg指向的動態數組的大小,之后由i索引msg i等於numMessmsg[i]越界。

那么這是怎么發生的呢?

string chars;
getline(in, chars); // this doesn't make much sense. Reconsider it
for (chars; std::getline(in, chars); i < numMess) {

這是出問題的地方。 for循環應類似於

for (initializer ; exit condition ; iterator to advance the loop)

for (chars; // does nothing. Compiler may be warning you
     std::getline(in, chars); // loop exits on failed read
     i < numMess) { // does nothing to advance the loop

這里沒有什么阻止i超過numMess因為i < numMess未被用作退出條件。 是的,但是為什么不std::getline(in, chars); 到達文件末尾時跳出循環? 文件末尾的空行。 chars已成功設置為空字符串。

for ( ; // nothing happening here
     i < numMess and std::getline(in, chars) ;
     ++i) { // and remove the ++i from the end of the loop.

使您擺脫當前的困境,並可能會為您提供滿足您需求的程序。 尚未測試。

但是,如果文件中有錯誤並且文件在到達numMess之前已退出numMess辦? 這就是PaulMckenzie想要的東西。 您最好不要完全信任numMess ,而選擇更類似的方法

int numMess = 0;
in >> numMess; // not that we care
vector<Messages> msg;

//read file
int i = 0;
string chars;
while (std::getline(in, chars)) { // get each line. Note this gets the empty line, too
    Messages temp; // make a temporary for storage

    temp.messageNum = i + 1;
    temp.codedMessage = chars;


    //decode file
    for (char &j : chars) {
        if (j - 'A' >= 0 && j - 'A' < 26)
            j = arr[j - 'A'];
    }
    temp.decodedMessage = chars;
    msg.push_back(temp);
}

暫無
暫無

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

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