0
typedef struct tape
{
    char symbol;
    struct tape *next;
    struct tape *prev;
}tape;

tape *pt;    

void GenerateInputTape(int n)
{
    int i;

    pt=(tape*)malloc(sizeof(tape));

    pt->symbol='B';

    pt->prev=NULL;
    pt->next=(tape*)malloc(sizeof(tape));
    pt=pt->next;

    for(i=0;i<2*(n+1);i++)
    {   
        if(i < (2*n/2))
            pt->symbol='0';
        else
            pt->symbol='1';

        pt->prev=pt;
        pt->next=(tape*)malloc(sizeof(tape));
        pt=pt->next;
    }

    pt->symbol='B';

    pt->next=NULL;
}

void ShowTape()
{
    //Move tape to the beginning
    while (pt->prev != NULL)
        pt=pt->prev; //crash point

    //List out all of the elements
    while ((pt->next) != NULL)
    {   
        printf("%c",pt->symbol);
        pt=pt->next;
    }
    puts("\n");
}

This is a code snippet of program that has been designed to create a doubly linked list, fill it with B0...n011....(n+1)1B chars and print them. Unfortunately, it crashes while traversing back. Why?

Unhandled exception at 0x771a15de in turing_machine.exe: 0xC0000005: Access violation reading location 0xcdcdcdd5.

0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65
  • 3
    Oh, implementing a Turing machine? :) –  Jan 11 '13 at 20:03
  • (However, this doesn't explain why you're casting the return value of `malloc()`...) –  Jan 11 '13 at 20:04
  • @H2CO3 Shh, it's a secret ;) – 0x6B6F77616C74 Jan 11 '13 at 20:05
  • @H2CO3 and `malloc()` is casted because I don't use a C++ complier. – 0x6B6F77616C74 Jan 11 '13 at 20:07
  • If you don't use a C++ compiler, then you don't need the cast. –  Jan 11 '13 at 20:07
  • 1
    I think you should `s/don't//` there, if you use a C compiler, you don't need the cast, if you use a C++ compiler, you do. – Daniel Fischer Jan 11 '13 at 20:08
  • I'm used to a C++ compiler, I didn't realise you didn't need to cast `malloc` with a C compiler. What a sheltered life I've lead! – Steve Jan 11 '13 at 20:09
  • 1
    @Steve Well, to enlighten you: [it's even doscouraged](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) :) –  Jan 11 '13 at 20:12
  • It compiles without casting , but IntelliSense throws a warning. Anyway, it doesn't makes an significant difference: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858 – 0x6B6F77616C74 Jan 11 '13 at 20:14
  • 1
    Thanks :) I live in a C++ world where I never use `malloc` and avoid `new` as much as I possibly can :) – Steve Jan 11 '13 at 20:15

1 Answers1

10

You're not setting pt->prev correctly.

Instead of

pt->prev=pt;
pt->next=(tape*)malloc(sizeof(tape));

try:

pt->next = malloc(sizeof(tape));
pt->next->prev = pt;
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Steve
  • 7,171
  • 2
  • 30
  • 52