SELECT ALL OPTIONS BELOW THAT ARE TRUE FOR THE GIVEN CODE #include <string.h> #include <stdlib.h> #include <stdio.h> #define MAX_STR_LEN 100 struct Node { char *data; struct Node *left; struct Node *right; }; struct Node *new_node(char *d) { struct Node *r = malloc(sizeof(struct Node)); r->data = malloc(sizeof(char) * MAX_STR_LEN); strncpy(r->data, d, MAX_STR_LEN); free(d); r->left = NULL; r->right = NULL; return r; } void freeSubTree(struct Node *r) { free(r->data); if (r->left != NULL) freeSubTree(r->left); if (r->right != NULL) freeSubTree(r->right); free(r); } void printSubTree(struct Node *r) { printf("%s ", r->data); if (r->left != NULL) printSubTree(r->left); if (r->right != NULL) printSubTree(r->right); } int main() { struct Node *root = new_node("ABC"); struct Node *left = new_node("DEF"); struct Node *right = new_node("GHI"); root->left = left; root->right = right; printSubTree(root); freeSubTree(root); }
OPTIONS:
a.Memory leak: a Node hasn't been freed by the end of the program
b.Memory leak: a Node's item array. Root cause of leak is in new_node()
c.Memory leak: a Node's item array. Root cause of leak is in freeSubTree()
d.Invalid free: when free called on a struct Node* in freeSubTree()
e.Invalid free: when free called on a char* in freeSubTree()
f.Invalid free: when free called on a char* in new_node()
g.No memory errors or leaks
h.memory error in printSubTree(): when dereferencing r
i.Memory error in freeSubTree(): when dereferencing r
j.Memory error in printf caused by invalid argument: r->data holds invalid address
malloc is used to allocate memory in heap dynamically or at the run time. In this process, operating system or compiler allocate requested memory the running process if available else malloc return NULL.
free is used to de-allocate the dynamically allocated memory back to operating system.
If this dynamically allocated memory is not de-allocated, operating system may not have enough memory to continue its function and it can result into program crash or even restart of the system. This problem is called memory leak.
In the above C program, only option 'f' is correct because it's trying to deallocate memory which is a string literal not a dynamically allocated memory and hence free doesn't have permission to de-allocate(write) it. All other options are false.
Get Answers For Free
Most questions answered within 1 hours.