简单的 c 程序在 windows 中崩溃

Simple c program crashes in windows

我是新手 c.I 有以下创建双链表的代码。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct Dnode
{
    char c;
    struct Dnode *left;
    struct Dnode *right;
}Dnode;
void insert(Dnode *,char);
void unshift(Dnode *,char);
void travel(Dnode *);
int main(){
    Dnode *cur =  (Dnode *)malloc(sizeof(Dnode));
    Dnode *head = NULL;
    head = cur;

    cur -> c = 'a';
    printf("Cur -> c: %c\n",cur->c);
    cur ->left = NULL;
    cur -> right = (Dnode *)malloc(sizeof(Dnode));
    cur->right->c = 'b';
    cur->right->left = cur;
    cur = cur->right;
    travel(head);
    system("pause");
    return 0;
}
void reset(Dnode *h){
    while(h->left)
        h=h->left;
}
void travel(Dnode *head){
    printf("Traversing all nodes of list:\n");
    while(head->right){
        printf("Received char from node %c\n",head->c);
        head = head->right;
    }
    //reset(head);
}
void insert(Dnode * d,char c){
    Dnode *t = d;
    while(t ->right)
        t=t->right;
    t->right = (Dnode *)malloc(sizeof(Dnode));
    if(t->right){
        t->right->c = c;
        t= t->right;
        t->right = t->left = NULL;
    }
}
void unshift(Dnode *d,char cc){
    Dnode *t =(Dnode *)malloc(sizeof(Dnode));
    t =  d->right;
    t->left =NULL;
    d->left = t;
    d = t;
}       

问题是在调用 travel() 之后所有的节点都被打印出来了。 它打印 "Received char from node a" 和 "Received char from node b"

但是 Windows 给我一个错误,说这个程序有 crashed.Any 个想法?我想要一个详细的答案,以避免将来出现类似的问题。

初始化后您的列表如下所示:

   head ------>  X  ------> Y ------> uninitialized
               / ^         /
              /  |        /
             /   \       /
     null<---     -------

所以在 travel 函数中,您首先在第一个循环中打印 X.c,然后在第二个循环中使用未初始化的指针。那会导致程序崩溃。

所以你需要添加:

cur->right->c = 'b';
cur->right->left = cur;
cur->right->right = NULL   // Add this line

到初始化。

另请注意,您没有 free 分配的资源。所以在 main 中(就在 return 之前)你应该这样做:

Dnode *tmp;
while(head){
    tmp = head;
    head = head->right;
    free(tmp);
}

顺便说一句 - 不要强制转换 malloc 返回的值。只要做 Dnode *cur = malloc(sizeof(Dnode));

顺便说一句 - 这一行:

cur = cur->right;

可以删除,因为cur以后不用了。