可以在复合语句中使用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编译的
发布于 2015-07-12 02:26:44
在这里的示例中不安全:
printf("%s\n", str_to_cstr(s));来自alloca的glibc documentation:
不要在函数调用的参数中使用alloca -你会得到不可预知的结果,因为alloca的堆栈空间会出现在堆栈中函数参数空间的中间。要避免的一个例子是foo (x,alloca (4),y)。
注意,({})不是一个复合语句,而是一个GNU 。
https://stackoverflow.com/questions/31360271
复制相似问题