1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
|
.\"
.\" Copyright (c) 1980, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" $OpenBSD: malloc.3,v 1.56 2008/11/02 14:42:01 otto Exp $
.\"
.Dd $Mdocdate: November 2 2008 $
.Dt MALLOC 3
.Os
.Sh NAME
.Nm malloc ,
.Nm calloc ,
.Nm realloc ,
.Nm free ,
.Nm cfree
.Nd memory allocation and deallocation
.Sh SYNOPSIS
.Fd #include <stdlib.h>
.Ft void *
.Fn malloc "size_t size"
.Ft void *
.Fn calloc "size_t nmemb" "size_t size"
.Ft void *
.Fn realloc "void *ptr" "size_t size"
.Ft void
.Fn free "void *ptr"
.Ft void
.Fn cfree "void *ptr"
.Ft char *
.Va malloc_options ;
.Sh DESCRIPTION
The
.Fn malloc
function allocates uninitialized space for an object whose
size is specified by
.Fa size .
The
.Fn malloc
function maintains multiple lists of free blocks according to size, allocating
space from the appropriate list.
.Pp
The allocated space is
suitably aligned (after possible pointer
coercion) for storage of any type of object.
If the space is of
.Em pagesize
or larger, the memory returned will be page-aligned.
.Pp
Allocation of a zero size object returns a pointer to a zero size object.
This zero size object is access protected, so any access to it will
generate an exception (SIGSEGV).
Many zero-sized objects can be placed consecutively in shared
protected pages.
The minimum size of the protection on each object is suitably aligned and
sized as previously stated, but the protection may extend further depending
on where in a protected zone the object lands.
.Pp
When using
.Fn malloc
be careful to avoid the following idiom:
.Bd -literal -offset indent
if ((p = malloc(num * size)) == NULL)
err(1, "malloc");
.Ed
.Pp
The multiplication may lead to an integer overflow.
To avoid this,
.Fn calloc
is recommended.
.Pp
If
.Fn malloc
must be used, be sure to test for overflow:
.Bd -literal -offset indent
if (size && num > SIZE_MAX / size) {
errno = ENOMEM;
err(1, "overflow");
}
.Ed
.Pp
The
.Fn calloc
function allocates space for an array of
.Fa nmemb
objects, each of whose size is
.Fa size .
The space is initialized to zero.
The use of
.Fn calloc
is strongly encouraged when allocating multiple sized objects
in order to avoid possible integer overflows.
.Pp
The
.Fn free
function causes the space pointed to by
.Fa ptr
to be either placed on a list of free pages to make it available for future
allocation or, if required, to be returned to the kernel using
.Xr munmap 2 .
If
.Fa ptr
is a null pointer, no action occurs.
.Pp
A
.Fn cfree
function is also provided for compatibility with old systems and other
.Nm malloc
libraries; it is simply an alias for
.Fn free .
.Pp
The
.Fn realloc
function changes the size of the object pointed to by
.Fa ptr
to
.Fa size
bytes and returns a pointer to the (possibly moved) object.
The contents of the object are unchanged up to the lesser
of the new and old sizes.
If the new size is larger, the value of the newly allocated portion
of the object is indeterminate and uninitialized.
If
.Fa ptr
is a null pointer, the
.Fn realloc
function behaves like the
.Fn malloc
function for the specified size.
If the space cannot be allocated, the object
pointed to by
.Fa ptr
is unchanged.
If
.Fa size
is zero and
.Fa ptr
is not a null pointer, the object it points to is freed and a new zero size
object is returned.
.Pp
When using
.Fn realloc
be careful to avoid the following idiom:
.Bd -literal -offset indent
size += 50;
if ((p = realloc(p, size)) == NULL)
return (NULL);
.Ed
.Pp
Do not adjust the variable describing how much memory has been allocated
until the allocation has been successful.
This can cause aberrant program behavior if the incorrect size value is used.
In most cases, the above sample will also result in a leak of memory.
As stated earlier, a return value of
.Dv NULL
indicates that the old object still remains allocated.
Better code looks like this:
.Bd -literal -offset indent
newsize = size + 50;
if ((newp = realloc(p, newsize)) == NULL) {
free(p);
p = NULL;
size = 0;
return (NULL);
}
p = newp;
size = newsize;
.Ed
.Pp
As with
.Fn malloc
it is important to ensure the new size value will not overflow;
i.e. avoid allocations like the following:
.Bd -literal -offset indent
if ((newp = realloc(p, num * size)) == NULL) {
...
.Ed
.Pp
Malloc will first look for a symbolic link called
.Pa /etc/malloc.conf
and next check the environment for a variable called
.Ev MALLOC_OPTIONS
and finally for the global variable
.Va malloc_options
and scan them for flags in that order.
Flags are single letters, uppercase means on, lowercase means off.
.Bl -tag -width indent
.It Cm A
.Dq Abort .
.Fn malloc
will coredump the process, rather than tolerate internal
inconsistencies or incorrect usage.
This is the default and a very handy debugging aid,
since the core file represents the time of failure,
rather than when the bogus pointer was used.
.It Cm D
.Dq Dump .
.Fn malloc
will dump statistics in a file called
.Pa malloc.out
at exit.
This option requires the library to have been compiled with -DMALLOC_STATS in
order to have any effect.
.It Cm F
.Dq Freeguard .
Enable use after free protection.
Unused pages on the freelist are read and write protected to
cause a segmentation fault upon access.
.It Cm G
.Dq Guard .
Enable guard pages.
Each page size or larger allocation is followed by a guard page that will
cause a segmentation fault upon any access.
.It Cm H
.Dq Hint .
Pass a hint to the kernel about pages we don't use.
If the machine is paging a lot this may help a bit.
.It Cm J
.Dq Junk .
Fill some junk into the area allocated.
Currently junk is bytes of 0xd0 when allocating; this is pronounced
.Dq Duh .
\&:-)
Freed chunks are filled with 0xdf.
.It Cm P
.Dq Move allocations within a page.
Allocations larger than half a page but smaller that a page
are aligned to the end of a page to catch buffer overruns in more
cases.
.It Cm R
.Dq realloc .
Always reallocate when
.Fn realloc
is called, even if the initial allocation was big enough.
This can substantially aid in compacting memory.
.\".Pp
.\".It Cm U
.\".Dq utrace .
.\"Generate entries for
.\".Xr ktrace 1
.\"for all operations.
.\"Consult the source for this one.
.It Cm X
.Dq xmalloc .
Rather than return failure,
.Xr abort 3
the program with a diagnostic message on stderr.
It is the intention that this option be set at compile time by
including in the source:
.Bd -literal -offset indent
extern char *malloc_options;
malloc_options = "X";
.Ed
.Pp
Note that this will cause code that is supposed to handle
out-of-memory conditions gracefully to abort instead.
.It Cm Z
.Dq Zero .
Fill some junk into the area allocated (see
.Cm J ) ,
except for the exact length the user asked for, which is zeroed.
.It Cm <
.Dq Half the cache size .
Decrease the size of the free page cache by a factor of two.
.It Cm >
.Dq Double the cache size .
Increase the size of the free page cache by a factor of two.
.El
.Pp
So to set a systemwide reduction of cache size and use guard pages:
.Dl # ln -s 'G\*(Lt' /etc/malloc.conf
.Pp
The
.Cm J
and
.Cm Z
flags are mostly for testing and debugging.
If a program changes behavior if either of these options are used,
it is buggy.
.Pp
The default number of free pages cached is 64.
.Sh RETURN VALUES
The
.Fn malloc
and
.Fn calloc
functions return a pointer to the allocated space if successful; otherwise,
a null pointer is returned and
.Va errno
is set to
.Er ENOMEM .
.Pp
The
.Fn free
and
.Fn cfree
functions return no value.
.Pp
The
.Fn realloc
function returns a pointer to the (possibly moved) allocated space
if successful; otherwise, a null pointer is returned and
.Va errno
is set to
.Er ENOMEM .
.Sh ENVIRONMENT
.Bl -tag -width Ev
.It Ev MALLOC_OPTIONS
See above.
.El
.Sh FILES
.Bl -tag -width "/etc/malloc.conf"
.It Pa /etc/malloc.conf
symbolic link to filename containing option flags
.El
.Sh DIAGNOSTICS
If
.Fn malloc ,
.Fn calloc ,
.Fn realloc ,
or
.Fn free
detect an error condition,
a message will be printed to file descriptor
2 (not using stdio).
Errors will result in the process being aborted,
unless the
.Cm a
option has been specified.
.Pp
Here is a brief description of the error messages and what they mean:
.Bl -tag -width Ds
.It Dq out of memory
If the
.Cm X
option is specified it is an error for
.Fn malloc ,
.Fn calloc ,
or
.Fn realloc
to return
.Dv NULL .
.It Dq malloc init mmap failed
This is a rather weird condition that is most likely to indicate a
seriously overloaded system or a ulimit restriction.
.It Dq bogus pointer (double free?)
An attempt to
.Fn free
or
.Fn realloc
an unallocated pointer was made.
.It Dq chunk is already free
There was an attempt to free a chunk that had already been freed.
.It Dq modified chunk-pointer
The pointer passed to
.Fn free
or
.Fn realloc
has been modified.
.It Dq recursive call
An attempt was made to call recursively into these functions, i.e., from a
signal handler.
This behavior is not supported.
In particular, signal handlers should
.Em not
use any of the
.Fn malloc
functions nor utilize any other functions which may call
.Fn malloc
(e.g.,
.Xr stdio 3
routines).
.It Dq unknown char in MALLOC_OPTIONS
We found something we didn't understand.
.It Dq malloc cache overflow/underflow
The internal malloc page cache has been corrupted.
.It Dq malloc free slot lost
The internal malloc page cache has been corrupted.
.It Dq guard size
An inconsistent guard size was detected.
.It any other error
.Fn malloc
detected an internal error;
consult sources and/or wizards.
.El
.Sh SEE ALSO
.Xr brk 2 ,
.Xr mmap 2 ,
.Xr munmap 2 ,
.Xr alloca 3 ,
.Xr getpagesize 3
.Sh STANDARDS
The
.Fn malloc
function conforms to
.St -ansiC .
.Sh HISTORY
The present implementation of
.Fn malloc
started out as a filesystem on a drum
attached to a 20-bit binary challenged computer built with discrete germanium
transistors, and it has since graduated to handle primary storage rather than
secondary.
.Pp
The main difference from other
.Fn malloc
implementations are believed to be that
the free pages are not accessed until allocated.
Most
.Fn malloc
implementations will store a data structure containing a,
possibly double-, linked list in the free chunks of memory, used to tie
all the free memory together.
That is a quite suboptimal thing to do.
Every time the free-list is traversed, all the otherwise unused, and very
likely paged out, pages get faulted into primary memory, just to see what
lies after them in the list.
.Pp
On systems which are paging, this can increase the page-faults
of a process by a factor of five.
|