RE: malloc(0) returns an invalid address

From: David Schwartz <davids_at_webmaster.com>
Date: Tue, 30 Nov 2004 21:40:25 -0800
> 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
Received on Wed Dec 01 2004 - 04:40:20 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:38:23 UTC