BUG: realloc(p,0) should be consistent with malloc(0)

Alejandro Colomar alx@kernel.org
Tue Jun 17 03:18:51 GMT 2025


On Tue, Jun 17, 2025 at 05:14:07AM +0200, Alejandro Colomar wrote:
> > So it is unrelated to whatever
> > malloc(0) returns - the requirement is to return NULL if the old block remains
> > valid or a non-NULL new block.
> 
> No?  glibc currently returns NULL and the old block is freed.
> 
> 	alx@debian:~/tmp$ cat r.c 
> 	#include <stdlib.h>
> 
> 	int
> 	main(void)
> 	{
> 		void  *p;
> 
> 		p = malloc(42);
> 		if (p == NULL)
> 			exit(1);
> 
> 		p = realloc(p, 0);
> 		if (p == NULL)
> 			exit(2);
> 
> 		exit(0);
> 	}
> 	alx@debian:~/tmp$ gcc -Wall -Wextra r.c 
> 	alx@debian:~/tmp$ ./a.out; echo $?
> 	2
> 
> And of course, realloc(p,0) has freed the original p.
> 
> In fact, my proposal more closely resembles your model.  Under my
> proposal, realloc(p,0) would return non-null, and the old block is
> invalid, which is exactly what you said.
> 

I didn't show it, but the old block is certainly freed.  Here's a
program that shows that:

	alx@debian:~/tmp$ cat r.c 
	#include <stdio.h>
	#include <stdlib.h>

	int
	main(void)
	{
		void  *p, *q;

		p = malloc(42);
		if (p == NULL)
			exit(1);

		q = realloc(p, 0);
		if (q == NULL)
			printf("realloc(p,0) == NULL\n");

		free(p);

		exit(0);
	}
	alx@debian:~/tmp$ gcc -Wall -Wextra r.c 
	r.c: In function ‘main’:
	r.c:17:9: warning: pointer ‘p’ used after ‘realloc’ [-Wuse-after-free]
	   17 |         free(p);
	      |         ^~~~~~~
	r.c:13:13: note: call to ‘realloc’ here
	   13 |         q = realloc(p, 0);
	      |             ^~~~~~~~~~~~~
	alx@debian:~/tmp$ ./a.out 
	realloc(p,0) == NULL
	free(): double free detected in tcache 2
	Aborted


-- 
<https://www.alejandro-colomar.es/>


More information about the Libc-alpha mailing list