📄 rts.c
字号:
#include <stdio.h>#include <string.h>#include "rts.h"/* This is part of the runtime system. It is linked with the C code * the compiler produces when compiling Asterix source. It is not part * of the compiler itself. */void runtime_error(const char *msg){ fprintf(stderr, "Runtime error: %s\n", msg); exit(1);}array new_array(int size, size_t bytes_per_element){ array a; size_t total_bytes; if (size < 0) runtime_error("creating array with negative size"); /* Koen: due to (weird) alignment rules the array header is NOT equal * to sizeof(a->size); there may be a gap between size and the data! */ total_bytes = sizeof(*a)-sizeof(a->data) + size * bytes_per_element; a = calloc(total_bytes, 1); if (a == 0) runtime_error("out of memory"); a->size = size; return a;}array string_const(int size, const char *str){ array a = new_array( size, 1); memcpy(a->data.c, str, size); return a;}void delete_array(array a){ free(a);}void *array_index(array a, size_t bytes_per_element, int index){ if (a == 0) runtime_error("indexing null reference"); /* Koen: new test for robustness avoids casting to unsiged */ if (index < 0 || a->size <= index) runtime_error("out of bound indexing"); return (char *) &a->data + index * bytes_per_element;}/* Koen: runtime check for null references requires additional code */int array_size(array a){ if (a == 0) runtime_error("taking the size of a null reference"); return a->size;}int main(int argc, char **argv){ extern int cb_main(array); int i, ret_val; array new_argv = new_array(argc, sizeof(array)); /* Koen: allocate I/O buffer for reporting runtime * errors BEFORE running out of memory */ fprintf( stderr, "%s", ""); for (i = 0; i < argc; i ++) { array *next_arg_adr = array_index(new_argv, sizeof(array), i); /* Koen: removed redundant copy */ *next_arg_adr = string_const(strlen(argv [i]), argv [i]); } for (i = 0; strings [i].c != 0; i ++) strings [i].a = string_const(strings [i].s, strings [i].c); ret_val = cb_main(new_argv); for (i = 0; strings [i].a != 0; i ++) free(strings [i].a); for (i = 0; i < argc; i ++) delete_array(* (array *) array_index(new_argv, sizeof(array), i)); delete_array(new_argv); return ret_val;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -