typedef struct node char name Node Node createchar message N
Solution
a) destroy(element) call tries to free the memory allocated by element. But, element->name was not dynamically allocated, as it points to statically allocated variable \'message\'. Note that \'message\' lies on stack, whereas dynamically allocated memory lies on heap
So, free( garbage_element->name ) is the instruction causing the segmentation fault
b) Both nodes created have same dynamically allocated memory for their variable \'name\'. So when we destroy element1, we free the memory allocated by copy. Now, when we try to destroy element2, we try to free memory allocated by copy again, which is errorneous
c) To cope with above problems, when creating node, we dynamically allocate memory for \'name\' variable of node class too i.e. change it to :
Node* create( char* message ){
Node* new_element = (Node*)malloc( sizeof(Node));
if( !new_element ){
printf(\"Out of memory\ \");
return NULL;
}
new_element->name = (char*)malloc( strlen(message) + 1);
strcpy( new_element->name, message );
return new_element;
}
