John Kananakis John Kananakis - 1 month ago 4x
C Question

Simple c program crashes in windows

I am new to c.I Have the following code which creates a double linked list.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef struct Dnode
char c;
struct Dnode *left;
struct Dnode *right;
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;
return 0;
void reset(Dnode *h){
void travel(Dnode *head){
printf("Traversing all nodes of list:\n");
printf("Received char from node %c\n",head->c);
head = head->right;
void insert(Dnode * d,char c){
Dnode *t = d;
while(t ->right)
t->right = (Dnode *)malloc(sizeof(Dnode));
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;

The problem is that after travel() is called all the nodes are printed out.
It prints "Received char from node a"
and "Received char from node b"

but then Windows is giving me an error that says that the program has crashed.Any ideas?I would like a detailed answer so as to avoid similar problems in the future.


After initialization your list looks like:

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

So in the travel function you start by printing X.c in the first loop and then use the uninitialized pointer in the second loop. That cause a program crash.

So you need to add:

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

to the initialization.

Also notice that you don't free the allocated resources. So in main (just before return) you should do:

Dnode *tmp;
    tmp = head;
    head = head->right;

BTW - Don't cast the value returned by malloc. Just do Dnode *cur = malloc(sizeof(Dnode));

BTW - this line:

cur = cur->right;

can be deleted as cur is not used afterwards.