首页 > 解决方案 > 函数创建链表,在运行结束时将其删除

问题描述

(英语不是我的母语,请见谅)

我的代码应该逐行遍历汇编文件,当它在模式“:”中找到标签时,它应该将其添加为链表的头部。

当我尝试调试该函数时,我实际上可以看到它按计划填充了链表。但是在文件的最后一行之后,它会删除所有内容,并且列表的开头变为 NULL。

当我尝试在循环结束后放置断点时,Visual 发出警告“当前不会命中此断点。调试器的目标代码类型的可执行代码没有与此行相关联'。

这是代码:

//function input: 1. files 2.head of linked list
//function finds label in file and add label to linked list 
//function used in the first iteration


void create_labels_list(int argc, char* argv[], label* head)
{
    char newline[MAX_LINE];
    FILE* assem_file = fopen(argv[1], "r");
    int line_count = 1;//we want to know the number of line of the label so we could get to it when needed
    if (assem_file == NULL)
    {
        exit(1);
    }
    else
    {
        while (fgets(newline, MAX_LINE + 1, assem_file) != NULL)//go over the assembly file, line by line
        {
            clean_line(newline, 0); //get rid of all residuals in line
            int i = 0;//index of the chars in the line
            char labelname[50];
            int labelpc = 0;
            for (i; newline[i] != '\0'; i++)//go over the line
            {
                if (newline[i] == ':')//sign that we have a label in the line. if we do, create a new label in the linked list
                {
                    labelpc = line_count;
                    copy_string(labelname, newline, 0, i - 1);
                    head = new_label_in_link_lst(head, labelpc, labelname);
                }
            }
            line_count++;
        }
    }
    fclose(assem_file);
}

几天前它工作了,我不知道我改变了什么毁了它。谢谢你!

标签: cdebugginglinked-listbreakpoints

解决方案


您的问题很可能在这里:void create_labels_list(int argc, char* argv[], label* head). 在这段代码中,head指针的值只存在于函数内部。从函数退出后,您传递给它的旧值将生效。

一般来说,您有两种解决方法:

  1. 从这个函数返回指针的值,类似于new_label_in_link_lst.
label *create_labels_list(int argc, char* argv[], label* head) {
   ...
   return head;
}

main () {
   label *head = NULL;
   ...
   head = create_labels_list(..., head);
   ...
}
  1. 或者您可以将您的头部地址传递给参数中的函数并使用重定向来更新其值。
void create_labels_list(int argc, char* argv[], label** head) {
   ...
   *head = new_label_in_link_lst(*head, labelpc, labelname)
   ...
}

main () {
   label *head = NULL;
   ...
   create_labels_list(..., &head);
   ...
}

推荐阅读