0037-malloc.c (904B)
1 #include <assert.h> 2 #include <stdlib.h> 3 4 /* 5 output: 6 7 end: 8 */ 9 10 int 11 check_test1(void **vec) 12 { 13 int i, cnt; 14 15 for (i = cnt = 0; i < 100; i++) { 16 if (vec[i]) 17 cnt++; 18 } 19 return cnt; 20 } 21 22 void 23 test() 24 { 25 int i,n, which, nalloc; 26 static void *p[100]; 27 28 nalloc = 0; 29 for (i = 0; i < 5000; i++) { 30 which = rand() % 2; 31 if (which == 0 && nalloc < 100) { 32 for (n = rand()%100; p[n]; n = rand()%100) 33 ; 34 p[n] = malloc(rand() + 1); 35 nalloc++; 36 } else if (nalloc > 0) { 37 n = rand() % 100; 38 if (p[n]) 39 nalloc--; 40 free(p[n]); 41 p[n] = NULL; 42 } 43 assert(check_test1(p) == nalloc); 44 } 45 46 for (i = 0; i < nalloc; i++) { 47 for (n = 0; n < 100 && !p[n]; n++) 48 ; 49 assert(n < 100); 50 free(p[n]); 51 p[n] = NULL; 52 } 53 assert(check_test1(p) == 0); 54 55 for (i = 0; i < 100; i++) 56 assert(p[i] == NULL); 57 /* TODO: Add a verifier here */ 58 } 59 60 int 61 main() 62 { 63 puts("testing"); 64 test(); 65 puts("done"); 66 67 return 0; 68 }