c - 链表 : Exception thrown: read access violation. B 为 0xCDCDCDCD

标签 c pointers exception linked-list nodes

<分区>

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

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

也许您打算改为编写 A->next = B;

关于c - 链表 : Exception thrown: read access violation. B 为 0xCDCDCDCD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54929032/

相关文章:

C : use pointer-content as an array parameter

C 在 execvp 中传递一个参数和两个参数

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

c - 我无法弄清楚下面的代码如何产生 fffffffaa 的输出,请帮助我理解?

fopen/fwrite 链的 PHPUnit 测试

c++ - std::exception::_Raise 和 std::exception::exception 上的 VC++ 链接器错误

c - 编写 VTK ASCII 遗留文件以在 VisIt 中绘制轮廓

c - 为什么我会得到一个 SIGSEGV with glib?

c++ - 从指向的对象本身有效地释放指针

c++ - 在 C++ 中给定指向它的指针,查找 3-D vector 中元素的位置