xref: /netbsd-src/lib/libc/stdlib/reallocarray.3 (revision 0a0e590de3419de4c48a01e3bcdff0ff8611e371)
1.\" $NetBSD: reallocarray.3,v 1.2 2015/02/05 22:05:33 christos Exp $
2.\"
3.Dd February 5, 2015
4.Dt REALLOCARRAY 3
5.Os
6.Sh NAME
7.Nm reallocarray
8.Nd reallocate memory for an array of elements checking for overflow
9.Sh SYNOPSIS
10.Vt #define _OPENBSD_SOURCE
11.In stdlib.h
12.Ft void *
13.Fo reallocarray
14.Fa "void *ptr"
15.Fa "size_t nmemb"
16.Fa "size_t size"
17.Fc
18.Sh DESCRIPTION
19The
20.Fn reallocarray
21function reallocates the pointer
22.Fa ptr
23to a size appropriate to handle an allocation of
24.Fa nmemb
25elements in an array where each of the array elements is
26.Fa size
27bytes using
28.Xr realloc 3
29and making sure that overflow does not happen in the multiplication of
30.Dq "nmemb * size" .
31.Pp
32This function is provided for source compatibility with
33.Ox
34and
35its use is discouraged in preference to
36.Xr reallocarr 3 .
37.Sh RETURN VALUES
38The
39.Fn reallocarray
40function will return
41.Dv NULL
42if there was overflow or if
43.Xr realloc 3
44failed setting
45.Va errno
46to
47.Dv EOVERFLOW
48or preserving the value from
49.Xr realloc 3 .
50.Sh SEE ALSO
51.Xr malloc 3 ,
52.Xr realloc 3 ,
53.Xr reallocarr 3
54.Sh STANDARDS
55.Fn reallocarray
56is an
57.Ox
58extension.
59.Sh HISTORY
60The
61.Fn reallocarray
62function first appeared in
63.Ox 5.6 .
64.Fn reallocarray
65was redesigned in
66.Nx 8
67as
68.Fn reallocarr 3 .
69For compatibility reasons it's available since
70.Nx 8
71in the
72.Vt _OPENBSD_SOURCE
73namespace.
74.Sh CAVEATS
75The
76.Fn reallocarray
77function was designed to facilitate safe,
78robust programming and overcome the shortcomings of the
79.Xr malloc 3
80and
81.Xr realloc 3
82functions by centralizing the overflow check in the multiplication of
83.Fa nmemb
84and
85.Fa size .
86.Pp
87There are still portability issues (it does not solve
88the
89.Dv 0
90sized allocation return ambiguity in the C standard: does
91.Fn reallocarray
92return
93.Dv NULL
94or a unique pointer to memory that cannot be accessed? Does a
95.Dv NULL
96mean that an error occurred, and can someone check
97.Dv errno
98in that case to find out what happened?).
99.Pp
100For this reason
101.Nx
102decided to go with an alternative implementation, and created
103.Xr reallocarr 3 .
104