xref: /openbsd-src/regress/lib/libc/malloc/malloc_general/malloc_general.c (revision 03adc85b7600a1f8f04886b8321c1c1c0c4933d4)
1 /*	$OpenBSD	*/
2 /*
3  * Copyright (c) 2017 Otto Moerbeek <otto@drijf.net>
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 
22 /* $define VERBOSE */
23 
24 #define N 1000
25 
26 size_t size(void)
27 {
28 	int p = arc4random_uniform(13) + 3;
29 	return arc4random_uniform(1 << p);
30 }
31 
32 void *a[N];
33 
34 extern char *malloc_options;
35 
36 int
37 main(int argc, char *argv[])
38 {
39 	int count, p, i;
40 	void * q;
41 	size_t sz;
42 
43 	if (argc == 1)
44 		errx(1, "usage: malloc_options");
45 
46 	malloc_options = argv[1];
47 
48 	for (count = 0; count < 800000; count++) {
49 		if (count % 10000 == 0) {
50 			printf(".");
51 			fflush(stdout);
52 		}
53 		p = arc4random_uniform(2);
54 		i = arc4random_uniform(N);
55 		switch (p) {
56 		case 0:
57 			if (a[i]) {
58 #ifdef VERBOSE
59 				printf("F %p\n", a[i]);
60 #endif
61 				free(a[i]);
62 				a[i] = NULL;
63 			}
64 			sz = size();
65 #ifdef VERBOSE
66 			printf("M %zu=", sz);
67 #endif
68 			a[i] = malloc(sz);
69 #ifdef VERBOSE
70 			printf("%p\n", a[i]);
71 #endif
72 			if (a[i])
73 				memset(a[i], 0xff, sz);
74 			break;
75 		case 1:
76 			sz = size();
77 #ifdef VERBOSE
78 			printf("R %p %zu=", a[i], sz);
79 #endif
80 			q = realloc(a[i], sz);
81 #ifdef VERBOSE
82 			printf("%p\n", q);
83 #endif
84 			if (q) {
85 				a[i]= q;
86 				if (a[i])
87 					memset(a[i], 0xff, sz);
88 			}
89 			break;
90 		}
91 	}
92 	for (i = 0; i < N; i++)
93 		free(a[i]);
94 	printf("\n");
95 	return 0;
96 }
97