【发布时间】: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->next;你确定你不是指A->next = B;吗?另外,0xCDCDCDCD是未初始化的内存。 -
包含值
0xCDCDCDCD的内存通常是未初始化的堆内存。 -
0xCDCDCDCDstackoverflow.com/a/127404/487892 -
为什么要手动创建列表?你应该利用函数...
-
仅供参考。以后可以进行段故障自诊断。这是您的代码的实时测试://segfault.stensal.com/a/MSZEWQwFZtNgiBNp
标签: c pointers exception linked-list nodes