Reputation: 1
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
struct node* nc(int data) {
struct node* temp = (struct node*)(malloc(sizeof(struct node)));
temp->data = data;
temp->next = NULL;
return temp;
}
int getcount(struct node* head){
int count = 0;
struct node* temp= head;
while(temp!=NULL){
count++;
temp=temp->next;
}
return count;
}
int getpositionofelement(int data,struct node* head){
int count=0;
while(head->data!=data){
count++;
head=head->next;
}
return count;
}
int main()
{
struct node h;
struct node* head = &h; //(struct node*)malloc(sizeof(struct node));
h.data=5;
struct node* a = nc(19);
struct node* b = nc(25);
struct node* c = nc(12);
h.next = a;
a->next=b;
b->next=c;
free(b);
int count = getcount(head);
printf("the count is %d \n",count);
int l = 5;
printf("the position of %d in linkedlist is %d \n",l,getpositionofelement(l,head));
while(head!=NULL){
printf("%d \n",head->data);
head=head->next;
}
}
When I free the node b
why isn't the linked list getting terminated at b
? How does the free()
function work after taking a pointer as argument?
Upvotes: 0
Views: 94
Reputation: 4647
free() deallocates memory from the heap, that's all. You need to set your pointer to null. Your pointer can contain an address to memory that's alreay been free'd: it 's an invalid address but it's still store-able in your pointer variable.
Upvotes: 1