int main(int argc, char *argv[])
{
- size_t offset, stacksize = 1;
- char *b = malloc(stacksize);
- b[0] = 0;
- char *ptr = b;
- struct nest *t, *callstack = NULL;
+ size_t offset, stacksize;
+ char *buf, *ptr;
+ struct nest *temp, *stack;
FILE *in;
if(argc != 2){
fprintf(stderr, "Usage: %s PROGRAM\n", argv[0]);
return EXIT_FAILURE;
}
-
+
+ if((buf = malloc(stacksize = 1)) == NULL){
+ perror("malloc");
+ return EXIT_FAILURE;
+ }
+ buf[0] = 0;
+ ptr = buf;
+
if((in = fopen(argv[1], "r")) == NULL){
perror("fopen");
return EXIT_FAILURE;
while(1){
switch(fgetc(in)){
case EOF:
- free(b);
+ free(buf);
return EXIT_SUCCESS;
case '>':
++ptr;
- if(ptr >= b+stacksize){
- offset = ptr-b;
- b = realloc(b, stacksize *= 2);
- ptr = b+offset;
+ if(ptr >= buf+stacksize){
+ offset = ptr-buf;
+ if((buf = realloc(buf, stacksize *= 2)) == NULL){
+ perror("realloc");
+ return EXIT_FAILURE;
+ }
+ ptr = buf+offset;
memset(ptr, 0, stacksize/2);
}
break;
case '<':
- if(ptr == b){
+ if(ptr == buf){
fprintf(stderr, "There is no stack position -1...\n");
return EXIT_FAILURE;
}
break;
case '[':
if(*ptr){
- t = callstack;
- callstack = malloc(sizeof(struct nest));
- callstack->next = t;
- if((callstack->pos = ftell(in)) == -1){
+ temp = stack;
+ if((stack = malloc(sizeof(struct nest))) == NULL){
+ perror("realloc");
+ return EXIT_FAILURE;
+ }
+ stack->next = temp;
+ if((stack->pos = ftell(in)) == -1){
perror("ftell");
return EXIT_FAILURE;
}
}
break;
case ']':
- if(fseek(in, callstack->pos-1, SEEK_SET) == -1){
+ if(fseek(in, stack->pos-1, SEEK_SET) == -1){
perror("fseek");
return EXIT_FAILURE;
}
- t = callstack;
- callstack = callstack->next;
- free(t);
+ temp = stack;
+ stack = stack->next;
+ free(temp);
break;
default:
break;