OBFI

Brainfuck Interpreter
git clone http://git.omkov.net/OBFI
Log | Tree | Refs | README | LICENCE | Download

AuthorJakob Wakeling <[email protected]>
Date2021-08-18 04:25:09
Commit35b4ead3ce7badaba4c81b493930f45a51eec9a7
Parent8636cc60be5f514cf5ef96e1d310df725cdb3d52

Add tape length flag

At present, increasing the tape length too far results in a segfault

Diffstat

M src/obfi.c | 23 +++++++++++++++++------

1 files changed, 17 insertions, 6 deletions

diff --git a/src/obfi.c b/src/obfi.c
index 7ed0754..6cbaa1f 100644
--- a/src/obfi.c
+++ b/src/obfi.c
@@ -39,14 +39,14 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE.
 #include <stdlib.h>
 #include <string.h>
 
-#define TAPELEN 30000
-
 static struct lop lops[] = {
 	{ "help",    ARG_NUL, 256 },
 	{ "version", ARG_NUL, 257 },
 	{ NULL, 0, 0 }
 };
 
+static size_t l = 30000;
+
 static inline int cmp(const char *s1, const char *s2);
 static inline int run(const char *b, const long *c);
 
@@ -54,8 +54,16 @@ static void hlp(void);
 static void ver(void);
 
 int main(int ac, char *av[]) { A0 = av[0];
-	struct opt opt = OPTGET_INIT; opt.str = ""; opt.lops = lops;
+	struct opt opt = OPTGET_INIT; opt.str = "l:"; opt.lops = lops;
 	for (int o; (o = optget(&opt, av, 1)) != -1;) switch (o) {
+	case 'l': {
+		register char *s = opt.arg; register int c;
+		for (l = 0; *s >= '0' && *s <= '9'; ++s) { c = *s - '0';
+			if (l > (SIZE_MAX - c) / 10) { break; } l = l * 10 + c;
+		}
+		
+		if (*s) { error(1, "%s: invalid tape length", opt.arg); } break;
+	}
 	case 256: { hlp(); return 0; }
 	case 257: { ver(); return 0; }
 	default: { return 1; }
@@ -153,8 +161,8 @@ static inline int cmp(const char *s1, const char *s2) {
 
 /* Execute an array of Brainfuck instructions */
 static inline int run(const char *fb, const long *fc) {
-	uint_fast8_t *M = calloc(TAPELEN, sizeof (*M)), *p = M;
-	if (!M) { return 1; }
+	uint8_t *M = calloc(l, sizeof (*M)), *p = M;
+	if (!M) { error(1, "%s", serr()); }
 
 	// Execute each optimised Brainfuck instruction
 	for (size_t i = 0; fb[i]; ++i) switch (fb[i]) {