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