xref: /netbsd-src/lib/libc/stdlib/malloc.3 (revision 76c7fc5f6b13ed0b1508e6b313e88e59977ed78e)
1.\" $NetBSD: malloc.3,v 1.48 2016/06/01 08:32:05 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 June 1, 2016
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.
147If
148.Ar size
149is 0, either
150.Dv NULL
151or a pointer that can be safely passed to
152.Xr free 3
153is returned.
154.Pp
155The
156.Fn free
157function returns no value.
158.Sh EXAMPLES
159When using
160.Fn malloc ,
161be careful to avoid the following idiom:
162.Bd -literal -offset indent
163if ((p = malloc(number * size)) == NULL)
164	err(EXIT_FAILURE, "malloc");
165.Ed
166.Pp
167The multiplication may lead to an integer overflow.
168To avoid this,
169.Xr reallocarr 3
170is recommended.
171.Pp
172If
173.Fn malloc
174must be used, be sure to test for overflow:
175.Bd -literal -offset indent
176if (size && number > SIZE_MAX / size) {
177	errno = EOVERFLOW;
178	err(EXIT_FAILURE, "allocation");
179}
180.Ed
181.Pp
182The above test is not sufficient in all cases.
183For example, multiplying ints requires a different set of checks:
184.Bd -literal -offset indent
185int num, size;
186\&.\&.\&.
187
188/* Avoid invalid requests */
189if (size < 0 || num < 0)
190	errc(1, EOVERFLOW, "overflow");
191
192/* Check for signed int overflow */
193if (size && num > INT_MAX / size)
194	errc(1, EOVERFLOW, "overflow");
195
196if ((p = malloc(size * num)) == NULL)
197	err(1, "malloc");
198.Ed
199.Pp
200Assuming the implementation checks for integer overflow as
201.Nx
202does, it is much easier to use
203.Fn calloc
204or
205.Xr reallocarr 3 .
206.Pp
207The above examples could be simplified to:
208.Bd -literal -offset indent
209ptr = NULL;
210if ((e = reallocarr(&ptr, num, size)))
211	errx(1, "reallocarr", strerror(e));
212.Ed
213.Bd -literal -offset indent
214or at the cost of initialization:
215if ((p = calloc(num, size)) == NULL)
216	err(1, "calloc");
217.Ed
218.Pp
219When using
220.Fn realloc ,
221one must be careful to avoid the following idiom:
222.Bd -literal -offset indent
223nsize += 50;
224
225if ((p = realloc(p, nsize)) == NULL)
226	return NULL;
227.Ed
228.Pp
229Do not adjust the variable describing how much memory has been allocated
230until it is known that the allocation has been successful.
231This can cause aberrant program behavior if the incorrect size value is used.
232In most cases, the above example will also leak memory.
233As stated earlier, a return value of
234.Dv NULL
235indicates that the old object still remains allocated.
236Better code looks like this:
237.Bd -literal -offset indent
238newsize = size + 50;
239
240if ((p2 = realloc(p, newsize)) == NULL) {
241
242	if (p != NULL)
243		free(p);
244
245	p = NULL;
246	return NULL;
247}
248
249p = p2;
250size = newsize;
251.Ed
252.Sh SEE ALSO
253.\" .Xr limits 1 ,
254.Xr madvise 2 ,
255.Xr mmap 2 ,
256.Xr sbrk 2 ,
257.Xr aligned_alloc 3 ,
258.Xr alloca 3 ,
259.Xr atexit 3 ,
260.Xr getpagesize 3 ,
261.Xr memory 3 ,
262.Xr posix_memalign 3 ,
263.Xr reallocarr 3
264.Pp
265For the implementation details, see
266.Xr jemalloc 3 .
267.Sh STANDARDS
268The
269.Fn malloc ,
270.Fn calloc ,
271.Fn realloc
272and
273.Fn free
274functions conform to
275.St -isoC .
276.Sh HISTORY
277A
278.Fn free
279internal kernel function and a predecessor to
280.Fn malloc ,
281.Fn alloc ,
282first appeared in
283.At v1 .
284The C Library functions
285.Fn alloc
286and
287.Fn free
288appeared in
289.At v6 .
290The functions
291.Fn malloc ,
292.Fn calloc ,
293and
294.Fn realloc
295first appeared in
296.At v7 .
297.Pp
298A new implementation by Chris Kingsley was introduced in
299.Bx 4.2 ,
300followed by a complete rewrite by Poul-Henning Kamp
301.Dq ( phk's malloc
302or
303.Dq new malloc )
304which appeared in
305.Fx 2.2
306and was included in
307.Nx 1.5
308and
309.Ox 2.0 .
310These implementations were all
311.Xr sbrk 2
312based.
313.Pp
314The
315.Xr jemalloc 3
316allocator became the default system allocator first in
317.Fx 7.0
318and then in
319.Nx 5.0 .
320