baum

diff baum.c @ 55:6279e5b14d9e

added error handling for fopen and malloc; code cleanups
author meillo@marmaro.de
date Sun, 16 Mar 2008 10:40:53 +0100
parents 6e46b106c334
children b7544f23673b 73de2151aebd
line diff
     1.1 --- a/baum.c	Sun Mar 02 16:43:07 2008 +0100
     1.2 +++ b/baum.c	Sun Mar 16 10:40:53 2008 +0100
     1.3 @@ -44,6 +44,10 @@
     1.4  struct Node* newNode(char* name, unsigned char value) {
     1.5  	struct Node* node;
     1.6  	node = (struct Node*) malloc(sizeof(struct Node));
     1.7 +	if (node == NULL) {
     1.8 +		perror("unable to allocate memory");
     1.9 +		exit(10);
    1.10 +	}
    1.11  	strcpy(node->name, name);
    1.12  	node->value = value;
    1.13  	node->right = 0;
    1.14 @@ -91,12 +95,13 @@
    1.15  
    1.16  /* print */
    1.17  void printNode(struct Node* node, int level) {
    1.18 -	if (node != NULL) {
    1.19 -		while (level-- > 0) {
    1.20 -			fprintf(stderr, "\t");
    1.21 -		}
    1.22 -		fprintf(stderr, "%s (%d|%c)\n", node->name, node->value, node->value);
    1.23 +	if (node == NULL) {
    1.24 +		return;
    1.25  	}
    1.26 +	while (level-- > 0) {
    1.27 +		fprintf(stderr, "\t");
    1.28 +	}
    1.29 +	fprintf(stderr, "%s (%d|%c)\n", node->name, node->value, node->value);
    1.30  }
    1.31  
    1.32  void printTree(struct Node* root, int level) {
    1.33 @@ -117,6 +122,10 @@
    1.34  	struct Stackitem* tmp;
    1.35  	struct Stackitem* new;
    1.36  	new = (struct Stackitem*) malloc(sizeof(struct Stackitem));
    1.37 +	if (new == NULL) {
    1.38 +		perror("unable to allocate memory");
    1.39 +		exit(10);
    1.40 +	}
    1.41  	new->node = node;
    1.42  	tmp = stack;
    1.43  	stack = new;
    1.44 @@ -154,9 +163,13 @@
    1.45  	last_indent = -1;
    1.46  	last_node = NULL;
    1.47  	file = fopen(filename, "r");
    1.48 +	if (file == NULL) {
    1.49 +		perror("unable to open file");
    1.50 +		exit(10);
    1.51 +	}
    1.52  
    1.53  	while ((c = getc(file)) != EOF) {
    1.54 -		if (c == '#') { /* comment */
    1.55 +		if (c == '#') {  /* comment */
    1.56  			while ((c = getc(file)) != '\n') {
    1.57  			}
    1.58  		}