0x6B6F77616C74
0x6B6F77616C74

Reputation: 2629

Crash traversing back doubly linked list

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.

Upvotes: 0

Views: 193

Answers (1)

Steve
Steve

Reputation: 7271

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;

Upvotes: 10

Related Questions