任何人都可以檢查並查看鏈接列表實現是否存在錯誤?嘗試迭代鏈表時,我不斷收到seg錯誤。鏈接列表執行
我想通過「process_command」中的「root」迭代鏈接列表,但是當我嘗試訪問root-> child時,會出現seg fault錯誤。
實現,我使用來標記一個字符串,並把它們放到一個鏈表節點
typedef struct _node {
struct _node *child;
char *command;
} Command_list;
兩個功能。
Command_list *process_command(char command_line[256])
{
printf("Command: %s", command_line);
//allocate space for root & child
Command_list *root = (Command_list*)malloc(sizeof (Command_list));
Command_list *child = (Command_list*)malloc(sizeof (Command_list));
char *token;
char *saveptr;
//get the first part of the string
token = strtok_r(command_line, " ", &saveptr);
//if the first word in the string is student
if(!strcmp(token, "student"))
{
//set the first word to the be root
root = insert_command(token, root);
printf("Current root command: %s \n", root->command);
child = root;
//get the next word from the string
token = strtok_r(NULL, " ", &saveptr);
//keep getting words from the list and store them in a linked-list
while(token != NULL)
{
child = insert_command(token, child);
token = strtok_r(NULL, " ", &saveptr);
}
}
return root;
}
Command_list *insert_command(char *value, Command_list *root)
{
printf("previous value: %s \n", root->command);
Command_list *child_node = (Command_list*)malloc(sizeof (Command_list));
//if the node being passed in is empty, store the value in itself
if(root->command == NULL){
root->command = value;
root->child = 0;
printf("Inserting value to root: %s \n", root->command);
return root;
}
//otherwise store the value in a child node
else
{
child_node->command = value;
child_node->child = 0;
printf("Inserting value to child node: %s \n", child_node->command);
return child_node;
}
}
編輯: 迭代代碼
{
....
Command_list *temp = (Command_list*)malloc(sizeof (Command_list));
temp = root;
while(temp != NULL){
printf("Command: %s\n", temp->command);
temp = temp->child;
....
}
補充說我使用迭代碼。 該代碼似乎在代碼塊中正常工作,但它在終端中的第一個輸出之後停止迭代。
你的調試器說了什麼?回溯在哪裏? –
最有可能不是你的問題,在這裏,但不要拋出'malloc'的返回,一般來說根本不會拋出,除非你知道你在做什麼:http://stackoverflow.com/questions/605845/do -i-cast-of-malloc –
編譯器認爲你正在投射'malloc()'的返回值並懲罰你。 – 2012-09-30 06:41:41