1

is it possible to use alloca inside compound statement? Example:

typedef struct
{
    size_t len;
    char* data;
} string_t;

#define str_to_cstr(str) \
({ \
    char* v = alloca(str.len + 1); \
    v[len] = 0; \
    memcpy(v, str.data, str.len); \
})

// ... and somewhere in deep space
int main()
{
    string_t s = {4, "test"};
    printf("%s\n", str_to_cstr(s));
    return 0;
}

From my experience it works well, but I am not sure it is safe. BTW, it compiled with gcc 4.8.4

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
user939407
  • 43
  • 1
  • 5

1 Answers1

3

Not safe in your example here:

 printf("%s\n", str_to_cstr(s));

From glibc documentation of alloca:

Do not use alloca inside the arguments of a function call—you will get unpredictable results, because the stack space for the alloca would appear on the stack in the middle of the space for the function arguments. An example of what to avoid is foo (x, alloca (4), y).

Note that ({}) is not a compound statement but a GNU C statement expression.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Hmm, I found quite weak point in "man alloca": `On many systems alloca() cannot be used inside the list of arguments of a function call, because the stack space reserved by alloca() would appear on the stack in the middle of the space for the function arguments` So, does it means, what some systems allow to use alloca inside the arguments? – user939407 Jul 11 '15 at 20:06
  • @user939407 it means you should not do it. – ouah Jul 12 '15 at 10:49