home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 10 / 10.iso / l / l350 / 3.ddi / EXAMPLES / MSC / LIST.C < prev    next >
Encoding:
C/C++ Source or Header  |  1993-01-11  |  1.6 KB  |  81 lines

  1. /* 
  2. LIST.C
  3. usage: list [nodesize]
  4. allocates and frees a lot of memory; uses linked list; 
  5.     can specify node size
  6.  
  7. real mode:
  8.     C:\>cl /AL list.c 
  9.     C:\>list
  10.  
  11. protected mode:
  12.     C:\>cl386 /c list.c
  13.     C:\>386link list @msc386
  14.     C:\>list
  15. */
  16.  
  17. #include <stdlib.h>
  18. #include <stdio.h>
  19. #include <malloc.h>
  20. #include <time.h>
  21.  
  22. typedef struct node {
  23.     unsigned long num;
  24.     void *data;
  25.     struct node *next;
  26.     } NODE;
  27.     
  28. main(int argc, char *argv[])
  29. {
  30.     NODE *p, *q;
  31.     time_t t1, t2, t3;
  32.     unsigned long nodes, freed;
  33.     unsigned nodesize = (argc > 1) ? atoi(argv[1]) : 512;
  34.     
  35.     time(&t1);
  36.     
  37.     for (q = NULL, nodes = 0; ; q->next = p)
  38.     {
  39.     p = q;
  40.         if ((q = malloc(sizeof(NODE))) == NULL)
  41.             break;
  42.         if ((q->data = malloc(nodesize)) == NULL)
  43.         {
  44.             free(q);
  45.             break;
  46.         }
  47.         q->num = nodes++;
  48.     }
  49.         
  50.     time(&t2);
  51.  
  52.     for (freed = nodes; p != NULL; p = q)
  53.     {
  54.     q = p->next;
  55.         if (p->num != --freed)
  56.     {
  57.             printf("list corrupt: freed=%lu num=%lu\n", 
  58.                 freed, p->num);
  59.         return 1;
  60.     }
  61.         free(p->data);
  62.         free(p);
  63.     }
  64.     if (freed != 0)
  65.     {
  66.         printf("list corrupt: allocated %lu blocks, freed %lu blocks\n",
  67.         nodes, nodes - freed);
  68.         return 1;
  69.     }
  70.  
  71.     time(&t3);
  72.     printf("\nAllocated %lu nodes, %uK\n",
  73.         nodes, (nodes * (sizeof(NODE)+nodesize)) >> 10);
  74.     printf("Total time: %lu seconds\n", t3 - t1);
  75.     printf("Allocate time: %lu, freeing time: %lu\n",
  76.         t2 - t1, t3 - t2);
  77.  
  78.     return 0;
  79. }
  80.  
  81.