Statement expressions problem returning arrays.
Andrew Haley
aph@redhat.com
Wed May 28 19:43:00 GMT 2008
Jamax wrote:
> Andrew Haley wrote:
>> Redirected to gcc-help.
>
> Ok thanks, I thought gcc-help was for command line options and such.
> I chopped down the quoted text to the case that works in gcc that
> you say is not valid:
>
>> Jamax wrote:
>>> struct copy { char buf[128]; };
>>> #define copyof(str) &({ struct copy cp; strcpy(cp.buf, str); cp; }).buf[0]
>> 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.
>
> The page on statement expressions says the "value of the
> subexpression serves as the value of the entire construct". So
> really it should be evaluating to a copy of buf, a copy of the
> struct, no? It seems like a structure or an array of a specific
> size could be a value ...
gcc treats it like
char *p
{
struct copy cp;
strcpy(cp.buf, str);
p = cp.buf;
}
> Similar to:
>
> struct timeval epochTime(void) {
> struct timeval result = { 0, 0 };
> return result;
> }
>
> ... or is that also invalid ?!
>> None of those is valid. This is:
>>
>> #define copyof(STR) ({ char *p = malloc (strlen (STR) + 1); strcpy (p, STR); p; })
>
> It seems like alloca should work and not leak memory like that
> (unless in a loop...).
Sure.
Andrew.
More information about the Gcc-help
mailing list