typedef struct node char name Node Node createchar message N

typedef struct node {char *name:} Node: Node* create(char* message) {Node *new_element = (Node*)malloc(sizeof(Node)); if (!new_element) {printf(\"Out of memory\ \"); return NULL;} new_element rightarrow name = message; return new element;} Void destroy(Node*garbage_element) {free(garbage_element rightarrow name); free(garbage_element);} Why will the following sequence of instructions cause a segmentation fault? char message[] = \"Hello World\"; Node *element = create(message); if (element) {printf(\"EIement is %s\ \", element rightarrow name); destroy(element);} What is the problem with the following sequence of instructions? char message[] = \"Hello World\"; char *copy = (char*)malloc(strlen(message)+1); strcpy(copy, message); Node *element1 = create(copy); Node *element2 = create(copy); if (element1) {destroy(element1);} if (element2) {destroy(element2);} Write a create function that avoids the problems above

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;
}

 typedef struct node {char *name:} Node: Node* create(char* message) {Node *new_element = (Node*)malloc(sizeof(Node)); if (!new_element) {printf(\

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site