modernc.org/ccgo/v3@v3.16.14/lib/testdata/CompCert-3.6/test/c/lists.c (about) 1 /* List manipulations */ 2 3 #include <stdio.h> 4 #include <stddef.h> 5 #include <stdlib.h> 6 7 struct list { int hd; struct list * tl; }; 8 9 struct list * buildlist(int n) 10 { 11 struct list * r; 12 if (n < 0) return NULL; 13 r = malloc(sizeof(struct list)); 14 r->hd = n; 15 r->tl = buildlist(n - 1); 16 return r; 17 } 18 19 struct list * reverselist (struct list * l) 20 { 21 struct list * r, * r2; 22 for (r = NULL; l != NULL; l = l->tl) { 23 r2 = malloc(sizeof(struct list)); 24 r2->hd = l->hd; 25 r2->tl = r; 26 r = r2; 27 } 28 return r; 29 } 30 31 struct list * reverse_inplace(struct list * l) 32 { 33 struct list * prev, * next; 34 35 prev = NULL; 36 while (l != NULL) { 37 next = l->tl; 38 l->tl = prev; 39 prev = l; 40 l = next; 41 } 42 return prev; 43 } 44 45 int checklist(int n, struct list * l) 46 { 47 int i; 48 for (i = 0; i <= n; i++) { 49 if (l == NULL) return 0; 50 if (l->hd != i) return 0; 51 l = l->tl; 52 } 53 return (l == NULL); 54 } 55 56 int main(int argc, char ** argv) 57 { 58 int n, niter, i; 59 struct list * l; 60 61 if (argc >= 2) n = atoi(argv[1]); else n = 1000; 62 if (argc >= 3) niter = atoi(argv[1]); else niter = 20000; 63 l = buildlist(n); 64 if (checklist(n, reverselist(l))) { 65 printf("OK\n"); 66 } else { 67 printf("Bug!\n"); 68 return 2; 69 } 70 for (i = 0; i < 2*niter + 1; i++) { 71 l = reverse_inplace(l); 72 } 73 if (checklist(n, l)) { 74 printf("OK\n"); 75 } else { 76 printf("Bug!\n"); 77 return 2; 78 } 79 return 0; 80 } 81