/******************************** * Example of a fragile program * for ECS 153. Find the flaws! * * Till Stegers, 10 Jan 2006 * * http://wwwcsif.cs.ucdavis.edu/~stegers/ecs153/fragile.c * ********************************/ #include #include #include /* Data structure for tree nodes */ typedef struct { char label; struct NODE* left; struct NODE* right; } NODE; /* Construct a binary tree from prefix notation. * Leafs are denoted as nodes with empty subtrees, * as in (a()()) for the singleton tree containing a. * example: (b(a()())(c(d()())(e()()))) corresponds to * * b * a c * d e * * empty tree: () * singleton tree: (a()()) */ NODE* parse_tree(char** prefix){ NODE *node; /* empty tree */ if ((*prefix)[1] == ')'){ /* printf("empty tree: ()\n"); */ *prefix += 2; return NULL; } node = (NODE*) malloc(sizeof(NODE)); /* get root */ node->label = (*prefix)[1]; /* printf("Node: %c\n", node->label); */ /* skip '(' and node label */ *prefix += 2; node->left = (struct NODE*) parse_tree(prefix); node->right = (struct NODE*) parse_tree(prefix); /* account for closing paren */ *prefix += 1; return node; } /* Free memory occupied by tree */ void free_tree(NODE* root){ if (root == NULL) { printf("Error! Tried to free NULL!\n"); return; } printf("(%c", root->label); if (root->left != NULL) free_tree((NODE*)root->left); else printf("()"); if (root->right != NULL) free_tree((NODE*)root->right); else printf("()"); free(root); printf(")"); } /* * Read in prefix traversal, construct tree, * free tree, then exit. */ int main(int argc, char **argv) { char input[100]; NODE* root; char * prefix; printf("Please enter tree in prefix traversal: \n"); while (gets(input) == NULL){ printf("Please enter tree in prefix traversal: \n"); } prefix = (char*) malloc(strlen(input)); strcpy(prefix, input); root = parse_tree(&prefix); if (root != NULL){ printf("Successfully created tree\n"); /* work with tree ... */ /* free tree */ printf("Freeing tree...\n"); free_tree((NODE*)root); printf("\n"); } else { printf("Tree empty or in wrong format\n"); return -1; } return 0; }