ted: new append from rob, avoids overflow in pointer arithmetic - plan9port - [fork] Plan 9 from user space
 (HTM) git clone git://src.adamsgaard.dk/plan9port
 (DIR) Log
 (DIR) Files
 (DIR) Refs
 (DIR) README
 (DIR) LICENSE
       ---
 (DIR) commit c51c29052ee4a356d345424249024c67c2ec05ae
 (DIR) parent 68a6e0c0d03af1026f1b903bb071977543b7a939
 (HTM) Author: Russ Cox <rsc@swtch.com>
       Date:   Tue, 12 Jan 2010 11:16:14 -0800
       
       ed: new append from rob, avoids overflow in pointer arithmetic
       
       R=rsc
       http://codereview.appspot.com/188041
       
       Diffstat:
         M src/cmd/ed.c                        |      24 ++++++++++++++----------
       
       1 file changed, 14 insertions(+), 10 deletions(-)
       ---
 (DIR) diff --git a/src/cmd/ed.c b/src/cmd/ed.c
       t@@ -829,33 +829,37 @@ putfile(void)
        int
        append(int (*f)(void), int *a)
        {
       -        int *a1, *a2, *rdot, nline, tl;
       +        int *a1, *a2, *rdot, nline, d;
        
                nline = 0;
                dot = a;
                while((*f)() == 0) {
                        if((dol-zero) >= nlall) {
                                nlall += 512;
       -                        a1 = realloc(zero, (nlall+5)*sizeof(int*));
       +                        a1 = realloc(zero, (nlall+50)*sizeof(int*));
                                if(a1 == 0) {
                                        error("MEM?");
                                        rescue();
                                }
       -                        tl = a1 - zero;        /* relocate pointers */
       -                        zero += tl;
       -                        addr1 += tl;
       -                        addr2 += tl;
       -                        dol += tl;
       -                        dot += tl;
       +                        /* relocate pointers; avoid wraparound if sizeof(int) < sizeof(int*) */
       +                        d = addr1 - zero;
       +                        addr1 = a1 + d;
       +                        d = addr2 - zero;
       +                        addr2 = a1 + d;
       +                        d = dol - zero;
       +                        dol = a1 + d;
       +                        d = dot - zero;
       +                        dot = a1 + d;
       +                        zero = a1;
                        }
       -                tl = putline();
       +                d = putline();
                        nline++;
                        a1 = ++dol;
                        a2 = a1+1;
                        rdot = ++dot;
                        while(a1 > rdot)
                                *--a2 = *--a1;
       -                *rdot = tl;
       +                *rdot = d;
                }
                return nline;
        }