xref: /netbsd-src/lib/libc/stdlib/malloc.3 (revision f89f6560d453f5e37386cc7938c072d2f528b9fa)
1.\" $NetBSD: malloc.3,v 1.41 2015/02/06 08:37:39 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 February 5, 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.Pp
216.Bd -literal -offset indent
217nsize += 50;
218
219if ((p = realloc(p, nsize)) == NULL)
220	return NULL;
221.Ed
222.Pp
223Do not adjust the variable describing how much memory has been allocated
224until it is known that the allocation has been successful.
225This can cause aberrant program behavior if the incorrect size value is used.
226In most cases, the above example will also leak memory.
227As stated earlier, a return value of
228.Dv NULL
229indicates that the old object still remains allocated.
230Better code looks like this:
231.Bd -literal -offset indent
232newsize = size + 50;
233
234if ((p2 = realloc(p, newsize)) == NULL) {
235
236	if (p != NULL)
237		free(p);
238
239	p = NULL;
240	return NULL;
241}
242
243p = p2;
244size = newsize;
245.Ed
246.Sh SEE ALSO
247.\" .Xr limits 1 ,
248.Xr madvise 2 ,
249.Xr mmap 2 ,
250.Xr sbrk 2 ,
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