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
@@ -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


Reply via email to