xref: /netbsd-src/lib/libc/stdlib/malloc.3 (revision 946379e7b37692fc43f68eb0d1c10daa0a7f3b6c)
1.\" $NetBSD: malloc.3,v 1.46 2015/11/07 18:46:37 wiz Exp $
2.\"
3.\" Copyright (c) 1980, 1991, 1993
4.\"	The Regents of the University of California.  All rights reserved.
5.\"
6.\" This code is derived from software contributed to Berkeley by
7.\" the American National Standards Committee X3, on Information
8.\" Processing Systems.
9.\"
10.\" Redistribution and use in source and binary forms, with or without
11.\" modification, are permitted provided that the following conditions
12.\" are met:
13.\" 1. Redistributions of source code must retain the above copyright
14.\"    notice, this list of conditions and the following disclaimer.
15.\" 2. Redistributions in binary form must reproduce the above copyright
16.\"    notice, this list of conditions and the following disclaimer in the
17.\"    documentation and/or other materials provided with the distribution.
18.\" 3. Neither the name of the University nor the names of its contributors
19.\"    may be used to endorse or promote products derived from this software
20.\"    without specific prior written permission.
21.\"
22.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32.\" SUCH DAMAGE.
33.\"
34.\"     @(#)malloc.3	8.1 (Berkeley) 6/4/93
35.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
36.\"
37.Dd July 26, 2015
38.Dt MALLOC 3
39.Os
40.Sh NAME
41.Nm malloc , calloc , realloc , free
42.Nd general purpose memory allocation functions
43.Sh LIBRARY
44.Lb libc
45.Sh SYNOPSIS
46.In stdlib.h
47.Ft void *
48.Fn malloc "size_t size"
49.Ft void *
50.Fn calloc "size_t number" "size_t size"
51.Ft void *
52.Fn realloc "void *ptr" "size_t size"
53.Ft void
54.Fn free "void *ptr"
55.Sh DESCRIPTION
56The
57.Fn malloc
58function allocates
59.Fa size
60bytes of uninitialized memory.
61The allocated space is suitably aligned (after possible pointer coercion)
62for storage of any type of object.
63.Pp
64The
65.Fn calloc
66function allocates space for
67.Fa number
68objects,
69each
70.Fa size
71bytes in length.
72The result is identical to calling
73.Fn malloc
74with an argument of
75.Dq "number * size" ,
76with the exception that the allocated memory is explicitly initialized
77to zero bytes.
78.Pp
79The
80.Fn realloc
81function changes the size of the previously allocated memory referenced by
82.Fa ptr
83to
84.Fa size
85bytes.
86The contents of the memory are unchanged up to the lesser of the new and
87old sizes.
88If the new size is larger,
89the value of the newly allocated portion of the memory is undefined.
90Upon success, the memory referenced by
91.Fa ptr
92is freed and a pointer to the newly allocated memory is returned.
93.Pp
94Note that
95.Fn realloc
96may move the memory allocation, resulting in a different return value than
97.Fa ptr .
98If
99.Fa ptr
100is
101.Dv NULL ,
102the
103.Fn realloc
104function behaves identically to
105.Fn malloc
106for the specified size.
107.Pp
108The
109.Fn free
110function causes the allocated memory referenced by
111.Fa ptr
112to be made available for future allocations.
113If
114.Fa ptr
115is
116.Dv NULL ,
117no action occurs.
118.Sh RETURN VALUES
119The
120.Fn malloc
121and
122.Fn calloc
123functions return a pointer to the allocated memory if successful; otherwise
124a
125.Dv NULL
126pointer is returned and
127.Va errno
128is set to
129.Er ENOMEM .
130.Pp
131The
132.Fn realloc
133function returns a pointer, possibly identical to
134.Fa ptr ,
135to the allocated memory
136if successful; otherwise a
137.Dv NULL
138pointer is returned, and
139.Va errno
140is set to
141.Er ENOMEM
142if the error was the result of an allocation failure.
143The
144.Fn realloc
145function always leaves the original buffer intact
146when an error occurs.
147.Pp
148The
149.Fn free
150function returns no value.
151.Sh EXAMPLES
152When using
153.Fn malloc ,
154be careful to avoid the following idiom:
155.Bd -literal -offset indent
156if ((p = malloc(number * size)) == NULL)
157	err(EXIT_FAILURE, "malloc");
158.Ed
159.Pp
160The multiplication may lead to an integer overflow.
161To avoid this,
162.Xr reallocarr 3
163is recommended.
164.Pp
165If
166.Fn malloc
167must be used, be sure to test for overflow:
168.Bd -literal -offset indent
169if (size && number > SIZE_MAX / size) {
170	errno = EOVERFLOW;
171	err(EXIT_FAILURE, "allocation");
172}
173.Ed
174.Pp
175The above test is not sufficient in all cases.
176For example, multiplying ints requires a different set of checks:
177.Bd -literal -offset indent
178int num, size;
179\&.\&.\&.
180
181/* Avoid invalid requests */
182if (size < 0 || num < 0)
183	errc(1, EOVERFLOW, "overflow");
184
185/* Check for signed int overflow */
186if (size && num > INT_MAX / size)
187	errc(1, EOVERFLOW, "overflow");
188
189if ((p = malloc(size * num)) == NULL)
190	err(1, "malloc");
191.Ed
192.Pp
193Assuming the implementation checks for integer overflow as
194.Nx
195does, it is much easier to use
196.Fn calloc
197or
198.Xr reallocarr 3 .
199.Pp
200The above examples could be simplified to:
201.Bd -literal -offset indent
202ptr = NULL;
203if ((e = reallocarr(&ptr, num, size)))
204	errx(1, "reallocarr", strerror(e));
205.Ed
206.Bd -literal -offset indent
207or at the cost of initialization:
208if ((p = calloc(num, size)) == NULL)
209	err(1, "calloc");
210.Ed
211.Pp
212When using
213.Fn realloc ,
214one must be careful to avoid the following idiom:
215.Bd -literal -offset indent
216nsize += 50;
217
218if ((p = realloc(p, nsize)) == NULL)
219	return NULL;
220.Ed
221.Pp
222Do not adjust the variable describing how much memory has been allocated
223until it is known that the allocation has been successful.
224This can cause aberrant program behavior if the incorrect size value is used.
225In most cases, the above example will also leak memory.
226As stated earlier, a return value of
227.Dv NULL
228indicates that the old object still remains allocated.
229Better code looks like this:
230.Bd -literal -offset indent
231newsize = size + 50;
232
233if ((p2 = realloc(p, newsize)) == NULL) {
234
235	if (p != NULL)
236		free(p);
237
238	p = NULL;
239	return NULL;
240}
241
242p = p2;
243size = newsize;
244.Ed
245.Sh SEE ALSO
246.\" .Xr limits 1 ,
247.Xr madvise 2 ,
248.Xr mmap 2 ,
249.Xr sbrk 2 ,
250.Xr aligned_alloc 3 ,
251.Xr alloca 3 ,
252.Xr atexit 3 ,
253.Xr getpagesize 3 ,
254.Xr memory 3 ,
255.Xr posix_memalign 3 ,
256.Xr reallocarr 3
257.Pp
258For the implementation details, see
259.Xr jemalloc 3 .
260.Sh STANDARDS
261The
262.Fn malloc ,
263.Fn calloc ,
264.Fn realloc
265and
266.Fn free
267functions conform to
268.St -isoC .
269.Sh HISTORY
270A
271.Fn free
272internal kernel function and a predecessor to
273.Fn malloc ,
274.Fn alloc ,
275first appeared in
276.At v1 .
277The C Library functions
278.Fn alloc
279and
280.Fn free
281appeared in
282.At v6 .
283The functions
284.Fn malloc ,
285.Fn calloc ,
286and
287.Fn realloc
288first appeared in
289.At v7 .
290.Pp
291A new implementation by Chris Kingsley was introduced in
292.Bx 4.2 ,
293followed by a complete rewrite by Poul-Henning Kamp
294.Dq ( phk's malloc
295or
296.Dq new malloc )
297which appeared in
298.Fx 2.2
299and was included in
300.Nx 1.5
301and
302.Ox 2.0 .
303These implementations were all
304.Xr sbrk 2
305based.
306.Pp
307The
308.Xr jemalloc 3
309allocator became the default system allocator first in
310.Fx 7.0
311and then in
312.Nx 5.0 .
313