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");
}
这是一个程序代码片段,它被设计用来创建一个双链表,用B0…n011....(n+1)1B字符填充它并打印它们。不幸的是,它在返回时崩溃了。为什么?
turing_machine.exe中0x771a15de的未处理异常:0xC0000005:读取位置0xcdcdcdd5.
您没有正确设置pt->prev
pt->prev=pt;
pt->next=(tape*)malloc(sizeof(tape));
试题:
pt->next = malloc(sizeof(tape));
pt->next->prev = pt;