home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_07_07 / v7n7028a.txt < prev    next >
Text File  |  1989-09-04  |  1KB  |  56 lines

  1. Listing 1
  2.  
  3. /*
  4.  * This program demonstrates the behavior of a flawed imple-
  5.  * mentation of strrchr when it tries to search a string
  6.  * that begins at the start of a memory segment.  This
  7.  * program has been compiled and tested with Microsoft C 5.1
  8.  * using the compact, large and huge memory models.
  9.  */
  10.  
  11. #include <dos.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14.  
  15. void trace(const char *p)
  16.     {
  17.     printf("  %p -> %s\n", p, p == NULL ? "NULL" : (char *)p);
  18.     }
  19.  
  20. char *strrchr(const char *s, int c)
  21.     {
  22.     const char *t;
  23.  
  24.     for (t = s + strlen(s); trace(t), t >= s; --t)
  25.         if (*t == (char)c)
  26.             return (char *)t;
  27.     return NULL;
  28.     }
  29.  
  30. void main(void)
  31.     {
  32.     char c;
  33.     char *p = "abcdefghijklmnopqrs";
  34.     char *q;
  35.     unsigned int segment, offset;
  36.  
  37.     printf("original string...\n");
  38.     trace(p);
  39.     segment = FP_SEG(p);
  40.     offset = FP_OFF(p);
  41.     if (offset != 0)
  42.         {
  43.         segment += (offset + 15) >> 4;
  44.         FP_SEG(p) = segment;
  45.         FP_OFF(p) = 0;
  46.         }
  47.     printf("sub-string to be searched...\n");
  48.     trace(p);
  49.     printf("character to be found? ");
  50.     scanf("%c", &c);
  51.     printf("calling strrchr...\n");
  52.     q = strrchr(p, c);
  53.     printf("value returned by strrchr...\n");
  54.     trace(q);
  55.     }
  56.