Home | History | Annotate | Download | only in tests
      1 #include <stdlib.h>
      2 #include <string.h>
      3 
      4 // This shows the case whereby subtraction between two pointers from
      5 // different segments can be used legitimately.
      6 
      7 // dest: stack, src: heap
      8 char* my_strcpy (char* dest, const char* src)
      9 {
     10    char c, *s = (char *) src;
     11    long off = dest - s;
     12    off = off - 1;
     13    do {
     14       c = *s++;
     15       s[off] = c;          // s + off == dest
     16    } while (c != '\0');
     17    return dest;
     18 }
     19 
     20 int main(void)
     21 {
     22    char* h  = "hello, world";
     23    char* p1 = strdup(h);
     24    char* p2 = strdup(h);
     25    char  u1[13];
     26    char  u2[13];
     27 
     28    // All these are legit
     29    p1[p2-p1] = 0;    // p-p   (must be BADSEG'd) // ea is p2[0]
     30    u1[p2-u1] = 0;    // p-?
     31    p1[u2-p1] = 0;    // ?-p   (must be BADSEG'd)
     32    u1[u2-u1] = 0;    // ?-?
     33 
     34    // All these are a 1-byte underrun
     35    p1[p2-p1-1] = 0;  // p-p   (must be BADSEG'd) // ea is p2[-1]
     36    u1[p2-u1-1] = 0;  // p-?   (undet)
     37    p1[u2-p1-1] = 0;  // ?-p   (must be BADSEG'd)
     38    u1[u2-u1-1] = 0;  // ?-?   (undet)
     39 
     40    my_strcpy(u1, p1);
     41    my_strcpy(u2, u1);
     42 
     43    return 0;
     44 }
     45