首页 > 解决方案 > 链表:抛出异常:读取访问冲突。B 是 0xCDCDCDCD

问题描述

我在下面的链接列表代码中发布了我的第一次尝试。目标是获得一个包含 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);
    }

}

标签: cpointersexceptionlinked-listnodes

解决方案


这是你的问题

B = A->next;

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

也许你打算改写A->next = B;


推荐阅读