【发布时间】:2019-02-06 20:47:52
【问题描述】:
我已经编写了一些代码来帮助我在程序中为更大的链表分隔破折号,但是当我调用该类时,我的代码卡在分隔符循环中并且不会死。我什至不能用 kill 命令杀死它 我必须打开一个新的 ssh 客户端
int deliminator(char word[], struct node *root){
struct node *start = (struct node*) malloc(sizeof(struct node));
struct node *trav = (struct node*) malloc(sizeof(struct node));
start->next= trav;
trav->prev = start;
char *token;
token = strtok(word,"-");
while(token){
/* this loop is broken */
printf("%s",token);
struct node *curr = (struct node*) malloc(sizeof(struct node));
strcpy(curr->set, token);
trav->next = curr;
curr->prev = trav;
trav = trav->next;
token = strtok(NULL,"-");
};
root->next = start;
return(0);
};
当我尝试通过循环不正确地运行 strtok 时 令牌 = strtok(令牌,“-”);它卡在第一个令牌上。我似乎找不到问题,我的一个朋友建议它与链表节点有关,但我删除了它们,我遇到了同样的问题。
我在此代码片段中调用分隔符类。
int main(int argc, char *argv[]){
struct node *root = (struct node*) malloc(sizeof(struct node));
struct node *trav = (struct node*) malloc(sizeof(struct node));
root->next = trav;
if(argc == 2){
/*only one giant string*/
deliminator(argv[1],root);
while(root->next!= NULL){
printf("%s",root->set);
};
【问题讨论】:
-
什么是
curr->set?在复制到它之前,你是否为它分配了内存? -
请显示您调用
deliminator的程序部分,特别是word的类型和初始化;同时显示struct node的定义。 -
你的循环
while(root->next!= NULL){ printf("%s",root->set); };永远不会改变root— 你需要在循环中的某处相当于root = root->next;的东西,担心是否可以改变root本身(它可能不是— 你需要它来释放内存)。 -
此外,您永远不会将 any 节点的
next指针设置为 null,并且不能安全地依赖malloc()为您执行此操作。您需要将next(和prev)指针显式设置为null,这是它们应该具有的值。 -
您的
deliminator函数创建了两个struct node对象,而不为它们的set成员分配任何东西,并将它们插入到列表中,位于您复制令牌的任何节点之前。当您随后在main()中打印这些节点的set成员时,您调用了未定义的行为。
标签: c linked-list strtok csv