【问题标题】:Function creating linked list, deletes it at the end of the run函数创建链表,在运行结束时将其删除
【发布时间】:2021-05-06 16:31:58
【问题描述】:

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

我的代码应该逐行检查一个汇编文件,当它在模式':'中找到标签时,它应该将其添加为链表的头部。

当我尝试调试该函数时,我实际上可以看到它按计划填充了链接列表。但在文件的最后一行之后,它会删除所有内容,并且列表的头部变为 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);
}

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

【问题讨论】:

  • 我试图将断点放在 while 循环的末尾。
  • 现在有点晚了,但是有了一个好的版本控制系统,您可以轻松跟踪所做的所有更改(假设您分别提交它们)。它还可以轻松回滚到以前的版本。即使对于小型业余项目,使用 VCS 也是一个好习惯。
  • 您实际上是如何将字符串值插入到链表中的?似乎问题是由错误使用指针引起的。您需要将字符串复制到列表注释中,否则它将不起作用。请编辑问题并插入链表数据结构。

标签: c debugging linked-list breakpoints


【解决方案1】:

您的问题很可能在这里: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);
   ...
}

【讨论】:

  • @Tom,在这种情况下,您应该将答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 2012-11-09
  • 2019-06-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多