2011-06-21 57 views
0

這真的讓我感到,我有一個程序,我也添加了一些額外的功能,我試圖做的一件事是實現一個鏈表。首先,一些代碼:指針分配導致程序停止

#include <stdio.h> 
#include "host.h" 
#include "misc.h" 
#include "machine.h" 

struct miss_pile{ 
    md_addr_t tag; 
    unsigned int isCon; 
    char block_type; 
    char culprit_type; 
    struct miss_pile * next; 

}*head=0, *linkPtr, *tail=NULL, *newLink; 
typedef struct miss_pile mp; 

void add_beg(md_addr_t new_tag/*int new_tag*/, char blk_type, char evicter_type){ 

    newLink = (mp *)malloc(sizeof(mp)); 
    newLink->tag = new_tag; 
    newLink->block_type = blk_type; 
    newLink->culprit_type = evicter_type; 
    newLink->isCon = 0; 

if (head == NULL){ 
    head=newLink; 
    head->next=NULL; 
    head->tag = new_tag; 
    head->block_type = blk_type; 
    head->culprit_type = evicter_type; 
    head->isCon=0; 
    } 
else if (head != NULL) 
    { 
    newLink->next=head; 
    head = newLink; 
    } 
} 

我已經確定,這條線是程序似乎停止

head=newLink;

一旦我排除這種代碼,程序運行正常,但當然其相當重要的代碼。任何幫助或見解將不勝感激!

需要注意的是,處理器在程序「坐」時保持100%。另外,我添加列表的程序是SimpleScalar的「sim-cache」模擬器。

+1

你在哪個系統上運行?我會嘗試在調試器中運行它,例如linux上的gdb或Windows上的內置Visual Studio。 GDB用-g標誌編譯你的程序。有很多關於gdb的教程,所以我不會讓你知道細節。 –

+0

我在虛擬機中運行Ubuntu 10.10。運行gdb提供了一些有用的信息,它似乎陷入了我的一些列表搜索循環中,我會仔細檢查它們並可能發佈它們。這可能是一項時間密集型任務嗎?這份名單很可能達到數十萬。但是,仍然限制簡單標量的指令數量,這應該使列表簡短,但是沒有效果。 – morgan

+0

我有一種感覺,有人會很快進來,並說:「不要投出'malloc()'」的結果:「) –

回答

1

首先,我認爲你可以簡化你的函數是這樣的:其次

void add_beg(md_addr_t new_tag/*int new_tag*/, char blk_type, char evicter_type){ 

    newLink = (mp *)malloc(sizeof(mp)); 
    newLink->tag = new_tag; 
    newLink->block_type = blk_type; 
    newLink->culprit_type = evicter_type; 
    newLink->isCon = 0; 
    /* on the first call, head is NULL, and it's exactly what we want */ 
    newLink->next = head; 
    /* then head point to the new element */ 
    head = newLink; 
} 

,我敢肯定,你的錯誤是從別的地方來在你的代碼,可能是與互動的一些其他功能你的全局變量頭部?或者它可能是其他任何東西:)

+0

啊,你先生是正確的,這個問題在我的代碼中的其他地方。我有一個設計不好的搜索循環; \t linkPtr = head; 而(linkPtr!= NULL) \t { \t如果(linkPtr->標記= fnd_tag!) \t \t {linkPtr = linkPtr->下;} \t否則{斷裂;} \t} – morgan