Re: Statement expressions problem returning arrays.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 




Andrew Haley wrote:
>Jamax wrote:
>> Andrew Haley wrote:
>>> 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.
>
>gcc treats it like
>
>char *p
>{
>  struct copy cp;
>  strcpy(cp.buf, str);
>  p = cp.buf;
>}

Ok, I understand now.  And I kind of put words in your mouth with the quoted example above due to editing and poor proofreading.  So there is actually nothing wrong with the following expression itself:

&({ struct copy cp; strcpy(cp.buf, str); cp; }).buf[0]

... it's just that once the address has been taken the 'returned' struct goes out of scope, and no longer exists so the address is invalid immediately (or never was valid?).  So even if one does:

void function(char *str) { ... }
function( &({ struct copy cp; strcpy(cp.buf, str); cp; }).buf[0] );

The address passed to function is already invalid before the function is called.  But probably the compiler doesn't actually 'deallocate' the space for it until the function returns, which is why this actually does work even though it shouldn't.

Thanks for taking the time to explain this cool feature, btw!

Jam




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux