【问题标题】:Linked list: Exception thrown: read access violation. B was 0xCDCDCDCD [duplicate]链表:抛出异常:读取访问冲突。 B是0xCDCDCDCD [重复]
【发布时间】:2019-07-22 13:34:31
【问题描述】:

我在下面的链接列表代码中发布了我的第一次尝试。目标是获得一个包含 10 个整数的链表,并遍历该链表以将奇数加倍,将偶数减半。由于我是链表的新手,所以我目前正在处理第一部分:生成列表。

从我看到的例子来看,我觉得没问题。它编译得很好,但是当我运行它时,我收到以下错误消息: “抛出异常:读取访问冲突。B 为 0xCDCDCDCD。” 这是在写着“C=B->next”的那一行。

有谁知道这意味着什么和/或为什么会发生? 任何输入将不胜感激:)

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

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

void freeList(struct node* head);

int main(void)
{
    srand(time(NULL));


    struct node * A = NULL;
    A = malloc(sizeof(struct node));
    struct node* B = malloc(sizeof(struct node));
    struct node* C = malloc(sizeof(struct node));
    struct node* D = malloc(sizeof(struct node));
    struct node* E = malloc(sizeof(struct node));
    struct node* F = malloc(sizeof(struct node));
    struct node* G = malloc(sizeof(struct node));
    struct node* H = malloc(sizeof(struct node));
    struct node* I = malloc(sizeof(struct node));
    struct node* J = malloc(sizeof(struct node));

    A->data = (rand() % 10) + 1;
    B->data = (rand() % 10) + 1;
    C->data = (rand() % 10) + 1;
    D->data = (rand() % 10) + 1;
    E->data = (rand() % 10) + 1;
    F->data = (rand() % 10) + 1;
    G->data = (rand() % 10) + 1;
    H->data = (rand() % 10) + 1;
    I->data = (rand() % 10) + 1;
    J->data = (rand() % 10) + 1;

    B = A->next;
    C = B->next;
    D = C->next;
    E = D->next;
    F = E->next;
    G = F->next;
    H = G->next;
    I = H->next;
    J = I->next;
    J->next = NULL;

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

    freeList(A);

    return 0; 
}

void freeList(struct node* A)
{ 
    struct node* temp;

    while (A != NULL)
    {
        temp = A;
        A = A->next;
        free(temp);
    }

}

【问题讨论】:

  • B = A-&gt;next; 你确定你不是指A-&gt;next = B; 吗?另外,0xCDCDCDCD 是未初始化的内存。
  • 包含值0xCDCDCDCD 的内存通常是未初始化的堆内存。
  • 为什么要手动创建列表?你应该利用函数...
  • 仅供参考。以后可以进行段故障自诊断。这是您的代码的实时测试://segfault.stensal.com/a/MSZEWQwFZtNgiBNp

标签: c pointers exception linked-list nodes


【解决方案1】:

您应该将节点分配给下一个指针,而不是相反。这就是节点链接的方式。

A->next = B;
B->next = C;
. 
.
. 

【讨论】:

    【解决方案2】:

    这是你的问题

    B = A->next;
    

    您从未为A-&gt;next 赋值,因此它未初始化。运行时环境在分配时用0xCDCDCDCD 填充A 指向的内存,以帮助您发现它没有被初始化。上面这行代码读取A-&gt;next的未初始化值,并将其存储在B中。这不是一个有效的指针地址!当您尝试取消引用无效指针 B 时,下一行代码 C = B-&gt;next; 会引发异常。

    也许您的意思是改为写A-&gt;next = B;

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-01
      • 2021-12-19
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多