malloc(0) returns an invalid address

David Schwartz davids at webmaster.com
Tue Nov 30 21:40:20 PST 2004


> In fact, if you compile the following code,
>
> #include <stdlib.h>
> #include <stdio.h>
>
> main()
> {
> 	char *p = malloc(0);
>
> 	printf("address of p is %p\n", p);
> 	*p = 0;			/* XXX */
> }
>
> the result of the execution would be as follows:
>
> % ./a.out
> address of p is 0x800
> zsh: 794 segmentation fault (core dumped)  ./a.out
>
> Is this a malloc bug?  Or is this the intended behavior and the man
> page description is old?

	This is the intended behavior but the man page description is correct. The
problem is not that the pointer is invalid but that you assumed that it was
large enough to hold a 'char' and it is not.

	DS




More information about the freebsd-current mailing list