1

是否可以在复合语句中使用 alloca ?例子:

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;
}

根据我的经验,它运作良好,但我不确定它是否安全。顺便说一句,它用 gcc 4.8.4 编译

4

1 回答 1

3

在您的示例中不安全:

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

来自 alloca 的 glibc文档

不要在函数调用的参数中使用 alloca——你会得到不可预知的结果,因为 alloca 的堆栈空间会出现在函数参数空间的中间的堆栈上。要避免的一个例子是 foo (x, alloca (4), y)。

请注意,这({})不是复合语句,而是 GNU C语句表达式

于 2015-07-11T18:26:44.373 回答