[hackers] [sbase] [PATCH] ed: Do not try to read-in a nonexistant file

From: Wolfgang Corcoran-Mathe <first.lord.of.teal_AT_gmail.com>
Date: Sat, 26 Dec 2015 17:02:39 -0500

This fixes a segfault caused by running ed with a
nonexistant filename argument, e.g. 'ed not_a_file_yet'.
---
 ed.c | 39 ++++++++++++++++++++++-----------------
 1 file changed, 22 insertions(+), 17 deletions(-)
diff --git a/ed.c b/ed.c
index 8903957..599e575 100644
--- a/ed.c
+++ b/ed.c
_AT_@ -609,26 +609,31 @@ doread(char *fname)
 
 	if (fp)
 		fclose(fp);
-	if (!(fp = fopen(fname, "r")))
-		error("input/output error");
 
-	curln = line2;
-	for (cnt = 0; (n = getline(&s, &len, fp)) > 0; cnt += (size_t)n) {
-		if (s[n-1] != '\n') {
-			if (len == SIZE_MAX || !(p = realloc(s, ++len)))
-				error("out of memory");
-			s = p;
-			s[n-1] = '\n';
-			s[n] = '\0';
+	if (access(fname, F_OK)) {
+		fprintf(stderr, "?%s\n", fname);  /* new file */
+	} else {
+		if (!(fp = fopen(fname, "r")))
+			error("input/output error");
+
+		curln = line2;
+		for (cnt = 0; (n = getline(&s, &len, fp)) > 0; cnt += (size_t)n) {
+			if (s[n-1] != '\n') {
+				if (len == SIZE_MAX || !(p = realloc(s, ++len)))
+					error("out of memory");
+				s = p;
+				s[n-1] = '\n';
+				s[n] = '\0';
+			}
+			inject(s);
 		}
-		inject(s);
+		printf("%zu\n", cnt);
+
+		aux = fp;
+		fp = NULL;
+		if (fclose(aux))
+			error("input/output error");
 	}
-	printf("%zu\n", cnt);
-
-	aux = fp;
-	fp = NULL;
-	if (fclose(aux))
-		error("input/output error");
 
 	if (savfname[0] == '\0') {
 		modflag = 0;
-- 
2.3.5
Received on Sat Dec 26 2015 - 23:02:39 CET

This archive was generated by hypermail 2.3.0 : Sat Dec 26 2015 - 23:12:12 CET