1 /*---------------------------------------------------------------------------
2  * Determine the malloc() overhead.
3  *
4  *---------------------------------------------------------------------------
5  * Utilityprogram for the configure script to estimate the overhead
6  * of the system malloc(). The algorithm is to allocate two blocks and
7  * measuring the difference in addresses. This is repeated for various
8  * block sizes and the minimum of the found differences is selected.
9  *
10  * Usage: overhead [--terse]
11  *
12  * If '--terse' is given, overhead prints just the number otherwise
13  * a nice message.
14  *
15  * Exit status is 1 if the overhead could not be determined.
16  *---------------------------------------------------------------------------
17  */
18 
19 #include <stdio.h>
20 #if defined(HAVE_STDLIB_H)
21 #  include <stdlib.h>
22 #endif
23 #ifdef HAVE_LIBC_H
24 #  include <libc.h>
25 #endif
26 #include <string.h>
27 
28 /*-------------------------------------------------------------------------*/
29 int
main(int argc,char ** argv)30 main (int argc, char **argv)
31 
32 {
33     int i, d, min;
34     char *p, *q;
35     int terse;
36     int total = 12, negative = 0, min_index = 0;
37 
38     terse = argc > 1 && !strcmp(argv[1], "--terse");
39 
40     i = 0x8000;
41     min = i;
42     d = i;
43     do
44     {
45 	p = malloc(i);
46 	q = malloc(i);
47 	total++;
48 	d = q - (p+i);
49 	if (d <= min)
50 	{
51 	    if (d < 0)
52 	    {
53 		negative++;
54 		if (negative*3 > total*2)
55 		{
56 		    fprintf(
57 		      stderr,
58 		      "Malloc returns does not return increasing addresses\n"
59 		    );
60 		    if (terse)
61 			printf("0");
62 		    exit(1);
63 		}
64 		continue;
65 	    }
66 	    if (d == min)
67 		break;
68 	    min = d;
69 	    min_index = i;
70 	    if (d == 0)
71 		break;
72 	}
73 	i -= sizeof(char *);
74     } while (i >= 0x7f00);
75 
76     d = 0x8000 - min_index;
77 
78     if (d > 0x100 || min > 0x1000)
79     {
80 	fprintf(stderr, "no credible value for EXTERN_MALLOC_OVERHEAD found\n");
81 	if (terse)
82 	    printf("0");
83 	fflush(stdout);
84 	exit(1);
85     }
86 
87     printf(terse ? "%d" : "Suggested EXTERN_MALLOC_OVERHEAD: %d\n", d);
88     if (!terse && d != min)
89 	printf("Actual overhead encountered for the above setting:%d\n", min);
90     return 0;
91 } /* main() */
92 
93 /***************************************************************************/
94 
95