2013-03-03 114 views
-1

我正在編寫反彙編程序,並使用鏈接列表來保存符號文件(sym_file)中的數據。我一直在看所有其他的帖子,但仍然無法實現它的工作! (保持分段錯誤)我想追加列表末尾的節點,這樣我就可以跟蹤head_node。將節點添加到單個鏈接列表中

void read_symbol_file(char* file_name) 
{ 
    struct node* head_node = new struct node; 
    struct node* node = new struct node; 
    struct node* temp; 
    ifstream sym_file(file_name, ios::out); 
    char label[16]; 
    char the_type[6]; 
    char address[6]; 

    if(sym_file.is_open()) 
    { 
     while (!sym_file.eof()) 
     { 
      sym_file >> label; 
      sym_file >> the_type; 
      sym_file >> address; 

      if(strcmp(the_type, "line") == 0) 
      { 
       node->type = line; 
       node->label = label; 
       node->address = atoi(address); 
      } 
      else if(strcmp(the_type, "block") == 0) 
      { 
       node->type = block; 
       node->label = label; 
       node->address = atoi(address); 
      } 
      else if(strcmp(the_type, "ascii") == 0) 
      { 
       node->type = ascii; 
       node->label = label; 
       node->address = atoi(address); 
      } 
      else if(strcmp(the_type, "word") == 0) 
      { 
       node->type = word; 
       node->label = label; 
       node->address = atoi(address); 
      } 
      else 
      { 
       cout << "invalid label" << endl; 
       exit(0); 
      } 

      if(head_node == NULL) 
      { 
       head_node = node; 
       head_node->next = node; 
      } 
      else 
      { 
       temp = head; 
       while(temp->next != NULL) 
        temp = temp->next; 
       temp->next = NULL; 
      } 
     } 
     sym_file.close(); 
    } 

    else 
    { 
     cout << "File does not exist or could not be found." << endl; 
     exit(0); 
    } 
    cout << head_node->label << endl; 

} 
+0

我希望我每次看到['while(!sym_file.eof())'在本網站上使用不正確](http://stackoverflow.com/q/5605125/78845)時有$ 1! – Johnsyweb 2013-03-03 11:24:33

+0

「不斷收到分段錯誤」。這應該可以幫助你追蹤錯誤。通過調試器運行此代碼,以查看您訪問的內存不屬於您的位置。通過只做一件事來減少函數的大小(追加到鏈表是與讀取文件完全不同的操作)。如果你仍然卡住,請發佈[簡短,獨立,正確(可編譯),示例](http://sscce.org/),我們會盡力協助。 – Johnsyweb 2013-03-03 20:47:17

回答

1

此行應該是一個編譯器錯誤:

  temp = head; 

因爲沒有一個變量「頭」的聲明

第二個問題是「新節點」的分配是外循環,所以你只有一個'節點'不斷被覆蓋。這行應該在'while'循環中移動:

struct node* node = new struct node; 

第三,else塊從不會將指向'node'的指針指定給下一個變量。應該是

temp->next = node; 

這段代碼中有幾個與head_node有關的其他問題,一旦它被分配,它將不會是== NULL。在將結構的地址分配給一個指針並將一個結構的內容拷貝到另一個結構(如在* head_node = * node中)之間似乎存在一些混淆。

在這種情況下,不需要使用'new'來分配head_node。這只是一個指針,可以初始化爲NULL。

+0

謝謝馬克。對於第一次修訂,我打算把temp = head_node;我將聲明移到了while循環中,並將temp-> next =節點添加到else語句中。我做了一些更多的測試,出於某種原因,temp-> next始終爲NULL,因此,「cout << head_node-> label << endl;」不打印任何東西。 – nLee 2013-03-03 04:51:31

+0

對不起,我沒有看到您的編輯前我轉貼。 – nLee 2013-03-03 05:00:38

+0

所以我做了一些改變,我的最後一個if-else語句如下: – nLee 2013-03-03 05:18:02