内存冲突问题,求解释。
程序代码:
#define _STDC_WANT_LIB_EXT1_1 #include <stdio.h> #include <stdlib.h> #include <ctype.h> typedef struct horse horse; struct horse { int age; char name[10]; char father[10]; char mother[10]; horse *next; horse *previous; }; int main () { horse *first=NULL; horse *current=NULL; horse *last=NULL; char test='\0'; for ( ; ;) { printf("Do you want to enter details of a%s horse (Y or N)",first==NULL?"":"nother"); scanf("%c",&test); if (tolower(test)=='n') { break; } current=(horse*)malloc(sizeof(horse)); if(first==NULL) { first=current; current->next=NULL; } else { last->next=NULL; current->previous=last; } printf("Please input the name of the horse:"); scanf("%s",current->name); putchar (10); printf("Please input the age of the horse:"); scanf("%d",¤t->age); putchar (10); printf("Please input the father of the horse:"); scanf("%s",current->father); putchar (10); printf("please input the mother of the horse:"); scanf("%s",current->mother); putchar (10); current->next=NULL; last=current; fflush(stdin); } putchar (10); while (current!=NULL) { printf("%s is %d years old,and its mother is %s,its father is %s",current->name,current->age,current->mother,current->father); last=current; current=current->previous; free(last); last=NULL; } first=NULL; system("pause"); return 0; }
本人使用visual c++2010编译器,编译无错误,一下是运行结果: