This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Statement expressions problem returning arrays.
- From: Andrew Haley <aph at redhat dot com>
- To: Jamax <codemonkey49 at earthlink dot net>
- Cc: "gcc-help at gcc dot gnu dot org" <gcc-help at gcc dot gnu dot org>
- Date: Wed, 28 May 2008 17:20:00 +0100
- Subject: Re: Statement expressions problem returning arrays.
- References: <1919643.1211990835431.JavaMail.root@elwamui-wigeon.atl.sa.earthlink.net>
Redirected to gcc-help.
Jamax wrote:
> Hello. I have some complex statement-expressions that I am having
> trouble with and this seemed like the more technical mailing list.
> I have boiled them down to these small examples:
>
> #1:
>
> #define copyof(str) ({ char buf[sizeof(str)]; strcpy(buf, str); buf; })
Don't do that: you'll be using buf outside its scope. The scope of
buf ends at the end of the block in which it is declared.
> int main(int argc, char **argv) {
> printf("%s %s\n", copyof("hello"), copyof("world"));
> }
>
> That produces the output "hello world" when compiled with no
> optimization, but "hello hello" when compiled with -O or greater
> (but not with just the flags enabled by -O). It was my impression
> that a character array allocated on the stack was kind of like a
> value rather than a pointer (like char arrays are inside a struct),
> so it seems like the statement-expression should be returning a copy
> of the whole array rather than a copy of a pointer to its previous
> location on the stack.
>
> #2
>
> #define copyof(str) ({ char buf[128]; strcpy(buf, str); buf; })
As above.
> int main(int argc, char **argv) {
> printf("%s %s\n", copyof("hello"), copyof("world"));
> }
>
> That produces "hello hello" no matter what optimization is used.
>
> #3:
>
> struct copy { char buf[128]; };
> #define copyof(str) ({ struct copy cp; strcpy(cp.buf, str); cp; }).buf
As above.
> int main(int argc, char **argv) {
> printf("%s %s\n", copyof("hello"), copyof("world"));
> }
>
> Memory fault.
>
> #4:
>
> struct copy { char buf[128]; };
> #define copyof(str) ({ struct copy cp; strcpy(cp.buf, str); cp; }).buf
As above.
> int main(int argc, char **argv) {
> printf("%s %s\n", copyof("hello"), copyof("world"));
> }
>
> That 'correctly' produces "hello world" with any optimization level.
>
> So my question is, are those all the expected behavior (#1 through
> #3 are not valid)? From my 'ok' knowledge of C and gnu extensions
> it seems like all four should produce "hello world".
None of those is valid. This is:
#define copyof(STR) ({ char *p = malloc (strlen (STR) + 1); strcpy (p, STR); p; })
Andrew.