Muhammad Hewedy Muhammad Hewedy - 1 month ago 10
C Question

GCC Statement Expression Issue

I just read about Statement Expressions Extension in GCC, and I found some unexpected behavior when using it.

Please observe this example:

#include <stdio.h>

int main(void)
{

char* res1 = ({
char arr[] ={'h', 'e', '\0'}; // was char *arr[]
arr[0] = 'x';
char* ptr = arr;
ptr;
});


char* res2 = ({
char arr[] ={'h', 'e', '\0'}; // was char *arr[]
arr[0] = 'X';
char* ptr = arr;
ptr;
});

printf ("%s %p\n", res1, res1);
printf ("%s %p\n", res2, res2);

return 0;
}


Output:

X 0x7fff93098160
X 0x7fff93098160


I noticing that, the variables
arr
in first block and
arr
in second block taking the same memory address.

Why that happening??

Answer

Both occurrences of arr are array objects with automatic storage duration; they're local to the enclosing block { ... } within the statement expression.

Each statement expression grabs the address of that local variable; that address is saved in res1 and res2and used *after* the end of the block, when the objectarr` no longer exists.

This is the same problem as a function returning the address of a local variable. The address becomes invalid when the variable ceases to exist, and the program's behavior is undefined.

So don't do that.