Reputation: 1976
I'm trying to implement a linked list in C:
#include <stdio.h>
#include <stdlib.h>
typedef struct el{
int number;
struct el *next;
} linkedlist;
linkedlist* newel(){
linkedlist *newelement = (linkedlist*)malloc(sizeof(linkedlist));
newelement->number = 10;
newelement->next=NULL;
return newelement;
}
void add(linkedlist **head, linkedlist *item){
if(!*head){
*head = item;
}
else{
item->next = *head;
*head = item;
}
}
void prnt(linkedlist *head){
while(head!=NULL){
printf("%d\n", head->number);
head=head->next;
}
}
int main(){
linkedlist *hd;
add(&hd,newel());
add(&hd,newel());
add(&hd,newel());
prnt(hd);
system("PAUSE");
return 0;
}
and I get:
Unhandled exception at 0x010c14e9 in test.exe: 0xC0000005: Access violation reading location 0xcccccccc.
I tried to debug and the problem is in prnt function. It seems it doesn't see NULL when head points to the last element... it's just going ahead. I have no idea how to fix it for now.
Upvotes: 1
Views: 279
Reputation: 20383
I think the cause of exception is that hd
is an uninitialized variable. In your environment, it seem to be carrying the value 0xcccccccc
. The check if(!*head)
probably never evaluated to be`true
.
Upvotes: 1
Reputation: 17585
linkedlist *hd;
This may lead to error. Because initially it may have some garbage
value. so you have to NULL to head linkedlist *hd = NULL;
Upvotes: 2