From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 19341 invoked by alias); 11 Oct 2005 20:03:17 -0000 Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org Received: (qmail 19320 invoked by uid 22791); 11 Oct 2005 20:03:15 -0000 Received: from yosemite.airs.com (HELO yosemite.airs.com) (205.217.158.180) by sourceware.org (qpsmtpd/0.30-dev) with SMTP; Tue, 11 Oct 2005 20:03:15 +0000 Received: (qmail 11838 invoked by uid 10); 11 Oct 2005 20:03:13 -0000 Received: (qmail 6257 invoked by uid 500); 11 Oct 2005 20:03:05 -0000 Mail-Followup-To: gcc-help@gcc.gnu.org, maa1666@yahoo.fr To: nrmj Cc: gcc-help@gcc.gnu.org Subject: Re: strict aliasing and pointer to struct References: <20051011093733.17209.qmail@web26908.mail.ukl.yahoo.com> From: Ian Lance Taylor Date: Tue, 11 Oct 2005 20:03:00 -0000 In-Reply-To: <20051011093733.17209.qmail@web26908.mail.ukl.yahoo.com> Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-SW-Source: 2005-10/txt/msg00053.txt.bz2 nrmj writes: > I have been googling a lot on the web about alias > analysis and strict aliasing, but haven't found much > about what is allowed or not when working with > structures. I don't think these questions have anything to do with gcc. I recommend that you ask on some place like comp.std.c. > 1) If I understand the C standard correctly, the > compiler is free to assume that two pointers pointing > to different types don't alias. > > If two struct have different tag name, like: > struct s1 {int i;}; > struct s2 {int i;}; > struct s1 *p1; > struct s2 *p2; > > p1 and p2 are considered by the compiler to point > to different locations and don't alias, because p1 > points to type "struct s1" and p2 points to type > "struct s2" which are different types, even if they > have the same members, right ? You have to watch out for the exception in C99 6.5.2.3 if there is a visible union declaration which contains both structs. But otherwise, yes, they are different types. > 2) Is it safe to cast pointer to struct B to pointer > to struct A, in order to fake inheritance, like in > this code sniplet ? No, that is not safe. But it is safe to do struct Color_Point { struct Point p; Color color; }; p = &my_color_point.p; > 3) When programming with socket, the following cast to > (struct sockaddr *) is very common. > But is it really safe ? > > struct sockaddr_in my_addr; > ... > bind(sockfd, (struct sockaddr *)&my_addr, > sizeof(struct sockaddr)); That is safe because the code does not dereference the resulting pointer. Ian