I'm trying to write a simple program that gets a list from the user (a list is a struct with data, and a pointer to the next list), and then print it. My code is working fine, but after printing, I get an error "Unhandled exception at 0x011e1502 in exercise 4.exe: 0xC0000005: Access violation reading location 0xcdcdcdcd."
Can anyone tell me why? here's my code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
typedef int list_data;
typedef struct list
{
list_data number;
struct list* next_list;
} list; //definition of a list
list* create_list()
{
list* anchor;
anchor=(list*)malloc(sizeof(list));
anchor->next_list=NULL;
return anchor; // allocates a memory for a list and returns address of first block
}
list* insert_list(list* current_position,list_data x)
{
list* temp;
temp=(list*)malloc(sizeof(list));
temp->number=x;
temp->next_list=current_position->next_list;
current_position->next_list=temp;
return temp; //inserts a new block with a data of x
}
void printlist(list* anchor)
{
list* current_list=anchor->next_list;
while(current_list!=NULL)
{
printf("%3d -> ",current_list->number);
current_list=current_list->next_list;
}
printf("End\n");
}
void scan_list(list* anchor)
{
int num1=1;
list* current_position=anchor;
printf("Enter values until 0\n");
while(num1!=0)
{
scanf("%d",&num1);
if(num1)
current_position=insert_list(current_position,num1);
}
}
void main()
{
list* anchor;
anchor=create_list();
scan_list(anchor);
printf("\n");
printlist(anchor);
free(anchor);
getch();
}