Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 20 Mar 2001 13:25:15 -0600
From:      seebs@plethora.net (Peter Seebach)
To:        tech-kern@netbsd.org, bsd hackers <freebsd-hackers@freebsd.org>
Subject:   Re: Question regarding the array of size 0. 
Message-ID:  <200103201925.f2KJPFO17440@guild.plethora.net>
In-Reply-To: Your message of "Tue, 20 Mar 2001 14:21:27 EST." <20010320142127.D6167@elfie.org> 

next in thread | previous in thread | raw e-mail | index | archive | help
In message <20010320142127.D6167@elfie.org>, John Franklin writes:
>On Tue, Mar 20, 2001 at 01:03:21PM -0600, Peter Seebach wrote:
>> In message <3AB7A76B.2BCF5D6E@net.com>, Shankar Agarwal writes:
>> >Can someone pls tell me if it is possible to define an array of size 0.
 
>> Not in C.

>Actually you can (see below).  It depends on the compiler and how strict
>you have it checking things.

The C language doesn't allow zero-sized objects.  Some systems may, but
C itself doesn't.

>What follows was done on a NetBSD 1.5 system.

More importantly, it was done with gcc, which (by default) compiles a
language called "GNU C", which is very similar to C, but has some extensions.

In C99, you can do this "portably" (C99 isn't exactly universally adopted yet)
by saying
	struct message {
		int header;
		char payload[];
	};

and then doing
	struct message *p;
	p = malloc(sizeof(struct message) + 10);
	p->header = 10;
	strcpy(p->payload, "123456789");

>int main()
>{
>        struct zero_array foo;
>
>        foo.header=1;
>        foo.payload[0]=10;
>        foo.payload[1]=12;

This isn't even a result of the page management, you're just overwriting
other space.

If you did
	struct zero_array foo;
	int a[2];
you would probably find that a[0] was 10, and a[1] was 12.  Probably.
The behavior is totally undefined, and it's not exactly reliable.  :)

-s

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




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