This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Statement expressions problem returning arrays.


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.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]