【问题标题】:why do I get this exception error-Unhandled exception thrown: write access violation. head was 0xFFFFFFFFCBB1E630为什么我会得到这个异常错误-抛出未处理的异常:写访问冲突。头是 0xFFFFFFFFCBB1E630
【发布时间】:2023-03-17 00:18:02
【问题描述】:

行头->data = (int)1; ,抛出上述异常 - 抛出未处理的异常:写访问冲突。头是 0xFFFFFFFFCBB1E630。可能是什么原因?

#include <stdio.h>
#include <conio.h>

void print_nodes(struct Node* head);

struct Node {
    int data;
    struct Node* next;
};

void print_nodes(struct Node* head) {
    struct Node* current = (struct Node*)malloc(sizeof(struct Node));

    while (current->next != NULL) {
        printf("%d", current->data);
    }
}

void main() {
    struct Node* head = (struct Node*)malloc(sizeof(struct Node));
    struct Node* first = (struct Node*)malloc(sizeof(struct Node));
    struct Node* second = (struct Node*)malloc(sizeof(struct Node));

    head->data = 1;
    head->next = first;

    first->data = 2;
    first->next = second;

    second->data = 3;
    second->next = NULL;

    print_nodes(head);
}

【问题讨论】:

  • current 的意义何在?只需使用headcurrent-&gt;next 未初始化。
  • 修复后,while (current-&gt;next != NULL) 将在current-&gt;next != NULL 时无限循环。应该是struct Node* current = head,在循环内是current = current-&gt;next。或者,直接在print_nodes() 中使用head,因为它是列表头部的副本
  • 在不包含&lt;stdlib.h&gt;&lt;malloc.h&gt; 的情况下如何编译?
  • 谢谢。你们都是对的。我必须分配 struct Node* current = head;并运行 while (current) 。我不再收到错误消息了。

标签: c


【解决方案1】:

print_nodes(),不需要分配。

//struct Node* current = (struct Node*)malloc(sizeof(struct Node));
struct Node* current = head;

更好的是,从head 而不是.next 开始。

void print_nodes(const struct Node* current) {
    while (current) {
        printf("%d", current->data);
        current = current->next
    }
}

【讨论】:

  • 谢谢。你帮我修好了
【解决方案2】:

你检查过 head 是否是一个有效的指针吗?应该不会吧。

struct Node* head = (struct Node*)malloc(sizeof(struct Node));
If(0==head) return 1;
head->data = 1;

【讨论】:

  • 这是一种很好的做法,但不是这里的故障原因。
  • 谢谢。我已经应用了你的建议。
猜你喜欢
  • 2019-12-31
  • 2020-10-24
  • 1970-01-01
  • 2021-10-26
  • 2017-01-27
  • 2018-11-16
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
相关资源
最近更新 更多