malloc.3: realloc() return value

One might be tempted to think that realloc() always requests a new
allocation before moving the contents over (at least in the case
where the new size is bigger than the original). This is not the
case; for example, on my system the following program:

	#include <stdlib.h>
	#include <stdio.h>
	#include <unistd.h>

	int main(int argc, char *argv[])
	{
		void *x = malloc(15);
		void *y = malloc(32);

		printf("x = %p\n", x);
		printf("y = %p\n", y);
		printf("usable_size(x) = %lu\n", malloc_usable_size(x));

		void *z = realloc(x, 24);
		printf("z = %p\n", z);

		return 0;
	}

prints:

	x = 0x1b3a010
	y = 0x1b3a030
	usable_size(x) = 24
	z = 0x1b3a010

Signed-off-by: Vegard Nossum <vegard.nossum@oracle.com>
Signed-off-by: Michael Kerrisk <mtk.manpages@gmail.com>
This commit is contained in:
Vegard Nossum 2020-02-08 16:37:14 +01:00 committed by Michael Kerrisk
parent f3aa51b217
commit 813d606b00
1 changed files with 6 additions and 3 deletions

View File

@ -216,9 +216,12 @@ function returns no value.
The
.BR realloc ()
function returns a pointer to the newly allocated memory, which is suitably
aligned for any built-in type and may be different from
.IR ptr ,
or NULL if the request fails.
aligned for any built-in type, or NULL if the request failed.
The pointer may be the same as
.IR ptr
if the allocation was not moved (e.g. there was room to expand the allocation in-place), or different from
.IR ptr
if the allocation was moved to a new address.
If
.I size
was equal to 0, either NULL or a pointer suitable to be passed to