Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 30 Nov 2004 21:40:25 -0800
From:      "David Schwartz" <davids@webmaster.com>
To:        <current@FreeBSD.org>
Subject:   RE: malloc(0) returns an invalid address
Message-ID:  <MDEHLPKNGKAHNMBLJOLKAEOHACAB.davids@webmaster.com>
In-Reply-To: <y7vis7mppd8.wl@ocean.jinmei.org>

next in thread | previous in thread | raw e-mail | index | archive | help

> 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




Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?MDEHLPKNGKAHNMBLJOLKAEOHACAB.davids>