Back to index

glibc  2.9
tst-qsort2.c
Go to the documentation of this file.
00001 #include <stdio.h>
00002 #include <stdlib.h>
00003 
00004 char *array;
00005 char *array_end;
00006 size_t member_size;
00007 
00008 int
00009 compare (const void *a1, const void *b1)
00010 {
00011   const char *a = a1;
00012   const char *b = b1;
00013 
00014   if (! (array <= a && a < array_end
00015         && array <= b && b < array_end))
00016     {
00017       puts ("compare arguments not inside of the array");
00018       exit (EXIT_FAILURE);
00019     }
00020   int ret = b[0] - a[0];
00021   if (ret)
00022     return ret;
00023   if (member_size > 1)
00024     return b[1] - a[1];
00025   return 0;
00026 }
00027 
00028 int
00029 test (size_t nmemb, size_t size)
00030 {
00031   array = malloc (nmemb * size);
00032   if (array == NULL)
00033     {
00034       printf ("%zd x %zd: no memory", nmemb, size);
00035       return 1;
00036     }
00037 
00038   array_end = array + nmemb * size;
00039   member_size = size;
00040 
00041   char *p;
00042   size_t i;
00043   size_t bias = random ();
00044   for (i = 0, p = array; i < nmemb; i++, p += size)
00045     {
00046       p[0] = (char) (i + bias);
00047       if (size > 1)
00048        p[1] = (char) ((i + bias) >> 8);
00049     }
00050 
00051   qsort (array, nmemb, size, compare);
00052 
00053   for (i = 0, p = array; i < nmemb - 1; i++, p += size)
00054     {
00055       if (p[0] < p[size]
00056          || (size > 1 && p[0] == p[size] && p[1] < p[size + 1]))
00057        {
00058          printf ("%zd x %zd: failure at offset %zd\n", nmemb,
00059                 size, i);
00060          free (array);
00061          return 1;
00062        }
00063     }
00064 
00065   free (array);
00066   return 0;
00067 }
00068 
00069 int
00070 main (int argc, char **argv)
00071 {
00072   int ret = 0;
00073   if (argc >= 2)
00074     ret |= test (atoi (argv[1]), atoi (argv[2]));
00075   else
00076     {
00077       ret |= test (10000, 1);
00078       ret |= test (200000, 2);
00079       ret |= test (2000000, 3);
00080       ret |= test (2132310, 4);
00081       ret |= test (1202730, 7);
00082       ret |= test (1184710, 8);
00083       ret |= test (272710, 12);
00084       ret |= test (14170, 32);
00085       ret |= test (4170, 320);
00086     }
00087 
00088   return ret;
00089 }