我正在使用C.我有一個主文件,它指向一個頭文件。我打算稱之爲「主要」和後者的實施「補充」。現在當我的Main文件運行時,它會從我的Supplement中調用一個函數。C Global Struct
該函數mallocs和編輯一個全局變量(在我的Supplement文件中)。繼續前進,我再次從我的Supplement文件中調用另一個函數。
現在這是問題所在,因爲每當我這樣做時我都會收到分段錯誤。使用gcc,我能夠發現在我的第二次函數調用期間,我編輯的全局變量似乎'消失'(打印顯示它在0x0地址並且不能訪問)。
I在C中是相當新的,我知道全局變量是不好的,但這是一個任務,因爲我們不能編輯Main文件,所以我只能在我的補充文件中使用全局變量來記住我的變量。
切割代號:
Main:
// call load
// check
Supplement:
typedef struct node
{
bool is_word;
struct node* children[27];
}node;
//Root Node
static node* root = NULL;
bool check(const char* word)
{
//edits word and puts it into input[i](as int)
for(int i=0;i<x;i++)
{
//uses root[input[i]] -this is the problem. Apparently root is 0x0.
}
}
bool load(const char* dictionary)
{
//mallocs and edits root. Note that it is quite a handful. Do note that in the context of this function, gdb returns seems to know root. It's just on the check function call that it mysteriously disappears.
//current = root
node* cur = root;
root = malloc(sizeof(node));
//Check if opened
if(dict==NULL)
{
return false;
}else
{
int ch = getc(dict);
while(ch!=EOF)
{
//if character is newline
if(ch==10)
{
cur->is_word = true;
cur = root;
dSize++;
}else{
int value = (ch==APOST)? 26 : ch-ASCII;
//if there are no nodes yet
if(cur->children[value]==NULL)
{
//make a new node
node* next = malloc(sizeof(node));
//point children to node
cur->children[value]= next;
//current becomes new node
cur= next;
}else{
//else, use node
cur=cur->children[value];
}
}
ch = getc(dict);
};
return true;
}
}
我其實設置root的變量。我不確定爲什麼我的代碼會引發這樣的評論。 我也通過在gdb上打印根證實了這一點。唯一的問題是在加載完成後,我運行檢查,root不見了。 在此先感謝!
你可以發佈一個最小的工作職能給予該變量的引用顯示問題的代碼示例? – Bakuriu
顯示代碼,比敘述更好。 – UmNyobe
你可以讓[SSCCE](http://sscce.org/)向我們展示?如果我們可以看到一些代碼,這會更容易。它甚至可以幫助你自己找到問題。 –