user939407
user939407

Reputation: 53

alloca inside compound statement

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

Upvotes: 2

Views: 181

Answers (1)

ouah
ouah

Reputation: 145899

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.

Upvotes: 3

Related Questions